- init changes

This commit is contained in:
Mustachedom committed 2026-08-17 03:49:37 -07:00
1 parent 8accf38f97
commit d6cffd01bc
38 files changed
+325 -3377

No files matched your search

-155
View File
@@ -1,155 +0,0 @@
Anim = Anim or {}
Ids = Ids or Require("lib/utility/shared/ids.lua")
Anim.Active = Anim.Active or {}
Anim.isUpdateLoopRunning = Anim.isUpdateLoopRunning or false
--- This will request the animation dictionary.
--- @param animDict string
--- @return boolean
function Anim.RequestDict(animDict)
if not animDict or type(animDict) ~= "string" then
return false
end
if HasAnimDictLoaded(animDict) then
return true
end
RequestAnimDict(animDict)
local timeout = GetGameTimer() + 2000
while not HasAnimDictLoaded(animDict) and GetGameTimer() < timeout do
Wait(50)
end
return HasAnimDictLoaded(animDict)
end
--- This will start the animation update loop.
function Anim.Start()
if Anim.isUpdateLoopRunning then return end
Anim.isUpdateLoopRunning = true
CreateThread(function()
while Anim.isUpdateLoopRunning do
local idsToProcess = {}
for idKey, _ in pairs(Anim.Active) do
table.insert(idsToProcess, idKey)
end
if #idsToProcess == 0 then
Wait(750)
else
for _, id in ipairs(idsToProcess) do
local animData = Anim.Active[id]
if animData then
local entity = animData.entity
local onComplete = animData.onComplete
if not DoesEntityExist(entity) then
if onComplete then onComplete(false, "despawned") end
Anim.Active[id] = nil
elseif animData.status == "pending_task" then
TaskPlayAnim(entity, animData.animDict, animData.animName, animData.blendIn, animData.blendOut, animData.duration, animData.flag, animData.playbackRate, false, false, false)
animData.startTime = GetGameTimer()
animData.animEndTime = animData.duration > 0 and (animData.startTime + animData.duration) or -1
animData.status = "playing"
elseif animData.status == "playing" then
local animationCompletedNaturally = false
if animData.duration == -1 then
if not IsEntityPlayingAnim(entity, animData.animDict, animData.animName, 3) and GetEntityAnimCurrentTime(entity, animData.animDict, animData.animName) > 0.8 then
animationCompletedNaturally = true
end
elseif animData.animEndTime ~= -1 and GetGameTimer() >= animData.animEndTime then
animationCompletedNaturally = true
end
if animationCompletedNaturally then
if onComplete then onComplete(true, "completed") end
Anim.Active[id] = nil
end
end
end
end
Wait(100)
end
end
end)
end
--- This will play an animation on the specified ped.
--- @param id string | nil
--- @param entity number
--- @param animDict string
--- @param animName string
--- @param blendIn number | nil
--- @param blendOut number | nil
--- @param duration number | nil
--- @param flag number | nil
--- @param playbackRate number | nil
--- @param onComplete function | nil
--- @return string | nil
function Anim.Play(id, entity, animDict, animName, blendIn, blendOut, duration, flag, playbackRate, onComplete)
local newId = id or Ids.CreateUniqueId(Anim.Active)
if Anim.Active[newId] then
if onComplete then
onComplete(false, "id_in_use")
end
return newId
end
if not entity or not DoesEntityExist(entity) or not IsEntityAPed(entity) then
if onComplete then
onComplete(false, "invalid_entity")
end
return nil
end
if not Anim.RequestDict(animDict) then
if onComplete then
onComplete(false, "dict_load_failed")
end
return nil
end
Anim.Active[newId] = {
entity = entity,
animDict = animDict,
animName = animName,
blendIn = blendIn or 8.0,
blendOut = blendOut or -8.0,
duration = duration or -1,
flag = flag or 1,
playbackRate = playbackRate or 0.0,
onComplete = onComplete,
status = "pending_task",
startTime = 0,
animEndTime = 0
}
Anim.Start()
return newId
end
function Anim.Stop(id)
if not id or not Anim.Active or not Anim.Active[id] then
return false
end
local animData = Anim.Active[id]
if animData.entity and DoesEntityExist(animData.entity) and IsEntityAPed(animData.entity) then
if animData.status == "playing" or animData.status == "pending_task" then
StopAnimTask(animData.entity, animData.animDict, animData.animName, 1.0)
end
end
if animData.onComplete then
animData.onComplete(false, "stopped_by_id")
end
Anim.Active[id] = nil
local anyLeft = Anim.Active and next(Anim.Active) ~= nil
if not anyLeft then
Anim.isUpdateLoopRunning = false
end
return true
end
return Anim
-143
View File
@@ -1,143 +0,0 @@
local Callback = {}
local CallbackRegistry = {}
-- Constants
local RESOURCE = GetCurrentResourceName() or 'unknown'
local EVENT_NAMES = {
CLIENT_TO_SERVER = RESOURCE .. ':CS:Callback',
SERVER_TO_CLIENT = RESOURCE .. ':SC:Callback',
CLIENT_RESPONSE = RESOURCE .. ':CSR:Callback',
SERVER_RESPONSE = RESOURCE .. ':SCR:Callback'
}
-- Utility functions
local function generateCallbackId(name)
return string.format('%s_%d', name, math.random(1000000, 9999999))
end
local function handleResponse(registry, name, callbackId, ...)
local data = registry[callbackId]
if not data then return end
if data.callback then
data.callback(...)
end
if data.promise then
data.promise:resolve({ ... })
end
registry[callbackId] = nil
end
local function triggerCallback(eventName, target, name, args, callback)
local callbackId = generateCallbackId(name)
local promise = promise.new()
CallbackRegistry[callbackId] = {
callback = callback,
promise = promise
}
if type(target) == 'table' then
for _, id in ipairs(target) do
TriggerClientEvent(eventName, tonumber(id), name, callbackId, table.unpack(args))
end
else
TriggerClientEvent(eventName, tonumber(target), name, callbackId, table.unpack(args))
end
if not callback then
local result = Citizen.Await(promise)
local returnResults = (result and type(result) == 'table' ) and result or {result}
return table.unpack(returnResults)
end
end
-- Server-side implementation
if IsDuplicityVersion() then
function Callback.Register(name, handler)
Callback[name] = handler
end
function Callback.Trigger(name, target, ...)
local args = { ... }
local callback = type(args[1]) == 'function' and table.remove(args, 1) or nil
return triggerCallback(EVENT_NAMES.SERVER_TO_CLIENT, target or -1, name, args, callback)
end
RegisterNetEvent(EVENT_NAMES.CLIENT_TO_SERVER, function(name, callbackId, ...)
if not name or not callbackId then return print(string.format("[%s] Warning: Invalid callback parameters - name: %s, callbackId: %s", RESOURCE, tostring(name), tostring(callbackId))) end
local handler = Callback[name]
if not handler then return end
local playerId = source
if not playerId or playerId == 0 then return print(string.format("[%s] Warning: Invalid source for callback '%s'", RESOURCE, name)) end
local result = table.pack(handler(playerId, ...))
TriggerClientEvent(EVENT_NAMES.CLIENT_RESPONSE, playerId, name, callbackId, table.unpack(result))
end)
RegisterNetEvent(EVENT_NAMES.SERVER_RESPONSE, function(name, callbackId, ...)
handleResponse(CallbackRegistry, name, callbackId, ...)
end)
-- Client-side implementation
else
local ClientCallbacks = {}
local ReboundCallbacks = {}
function Callback.Register(name, handler)
ClientCallbacks[name] = handler
end
function Callback.RegisterRebound(name, handler)
ReboundCallbacks[name] = handler
end
function Callback.Trigger(name, ...)
local args = { ... }
local callback = type(args[1]) == 'function' and table.remove(args, 1) or nil
local callbackId = generateCallbackId(name)
local promise = promise.new()
CallbackRegistry[callbackId] = {
callback = callback,
promise = promise
}
TriggerServerEvent(EVENT_NAMES.CLIENT_TO_SERVER, name, callbackId, table.unpack(args))
if not callback then
local result = Citizen.Await(promise)
return table.unpack(result)
end
end
RegisterNetEvent(EVENT_NAMES.CLIENT_RESPONSE, function(name, callbackId, ...)
if ReboundCallbacks[name] then
ReboundCallbacks[name](...)
end
handleResponse(CallbackRegistry, name, callbackId, ...)
end)
RegisterNetEvent(EVENT_NAMES.SERVER_TO_CLIENT, function(name, callbackId, ...)
local handler = ClientCallbacks[name]
if not handler then return end
local result = table.pack(handler(...))
TriggerServerEvent(EVENT_NAMES.SERVER_RESPONSE, name, callbackId, table.unpack(result))
end)
end
-- Exports
exports('Callback', Callback)
exports('RegisterCallback', Callback.Register)
exports('TriggerCallback', Callback.Trigger)
if not IsDuplicityVersion() then
exports('RegisterRebound', Callback.RegisterRebound)
end
return Callback
-394
View File
@@ -1,394 +0,0 @@
-- Cutscene Manager for FiveM
-- Handles cutscene loading, playback, and character management
---@class Cutscene
Cutscenes = Cutscenes or {}
Cutscene = Cutscene or {}
Cutscene.done = true
-- Constants
local LOAD_TIMEOUT <const> = 10000
local FADE_DURATION <const> = 1000
local CUTSCENE_WAIT <const> = 1000
-- Character model definitions
local characterTags <const> = {
{ male = 'MP_1' },
{ male = 'MP_2' },
{ male = 'MP_3' },
{ male = 'MP_4' },
{ male = 'MP_Male_Character', female = 'MP_Female_Character' },
{ male = 'MP_Male_Character_1', female = 'MP_Female_Character_1' },
{ male = 'MP_Male_Character_2', female = 'MP_Female_Character_2' },
{ male = 'MP_Male_Character_3', female = 'MP_Female_Character_3' },
{ male = 'MP_Male_Character_4', female = 'MP_Female_Character_4' },
{ male = 'MP_Plane_Passenger_1' },
{ male = 'MP_Plane_Passenger_2' },
{ male = 'MP_Plane_Passenger_3' },
{ male = 'MP_Plane_Passenger_4' },
{ male = 'MP_Plane_Passenger_5' },
{ male = 'MP_Plane_Passenger_6' },
{ male = 'MP_Plane_Passenger_7' },
{ male = 'MP_Plane_Passenger_8' },
{ male = 'MP_Plane_Passenger_9' },
}
-- Component definitions for character customization
local componentsToSave <const> = {
-- Components
{ name = "head", id = 0, type = "drawable" },
{ name = "beard", id = 1, type = "drawable" },
{ name = "hair", id = 2, type = "drawable" },
{ name = "arms", id = 3, type = "drawable" },
{ name = "pants", id = 4, type = "drawable" },
{ name = "parachute", id = 5, type = "drawable" },
{ name = "feet", id = 6, type = "drawable" },
{ name = "accessories", id = 7, type = "drawable" },
{ name = "undershirt", id = 8, type = "drawable" },
{ name = "vest", id = 9, type = "drawable" },
{ name = "decals", id = 10, type = "drawable" },
{ name = "jacket", id = 11, type = "drawable" },
-- Props
{ name = "hat", id = 0, type = "prop" },
{ name = "glasses", id = 1, type = "prop" },
{ name = "ears", id = 2, type = "prop" },
{ name = "watch", id = 3, type = "prop" },
{ name = "bracelet", id = 4, type = "prop" },
{ name = "misc", id = 5, type = "prop" },
{ name = "left_wrist", id = 6, type = "prop" },
{ name = "right_wrist", id = 7, type = "prop" },
{ name = "prop8", id = 8, type = "prop" },
{ name = "prop9", id = 9, type = "prop" },
}
-- Utility Functions
function table.shallow_copy(t)
local t2 = {}
for k, v in pairs(t) do
t2[k] = v
end
return t2
end
local function WaitForModelLoad(modelHash)
local timeout = GetGameTimer() + LOAD_TIMEOUT
while not HasModelLoaded(modelHash) and GetGameTimer() < timeout do
Wait(0)
end
return HasModelLoaded(modelHash)
end
local function CreatePedFromModel(modelName, coords)
local model = GetHashKey(modelName)
RequestModel(model)
if not WaitForModelLoad(model) then
print("Failed to load model: " .. modelName)
return nil
end
local ped = CreatePed(0, model, coords.x, coords.y, coords.z, 0.0, true, false)
if not DoesEntityExist(ped) then
print("Failed to create ped from model: " .. modelName)
return nil
end
return ped
end
-- Cutscene Core Functions
local function LoadCutscene(cutscene)
assert(cutscene, "Cutscene.Load called without a cutscene name.")
local playbackList = IsPedMale(PlayerPedId()) and 31 or 103
RequestCutsceneWithPlaybackList(cutscene, playbackList, 8)
local timeout = GetGameTimer() + LOAD_TIMEOUT
while not HasCutsceneLoaded() and GetGameTimer() < timeout do
Wait(0)
end
if not HasCutsceneLoaded() then
print("Cutscene failed to load: ", cutscene)
return false
end
return true
end
local function GetCutsceneTags(cutscene)
if not LoadCutscene(cutscene) then return end
StartCutscene(0)
Wait(CUTSCENE_WAIT)
local tags = {}
for _, tag in pairs(characterTags) do
if DoesCutsceneEntityExist(tag.male, 0) or DoesCutsceneEntityExist(tag.female, 0) then
table.insert(tags, tag)
end
end
StopCutsceneImmediately()
Wait(CUTSCENE_WAIT * 2)
return tags
end
-- Character Outfit Management
local function SavePedOutfit(ped)
local outfitData = {}
for _, component in ipairs(componentsToSave) do
if component.type == "drawable" then
outfitData[component.name] = {
id = component.id,
type = component.type,
drawable = GetPedDrawableVariation(ped, component.id),
texture = GetPedTextureVariation(ped, component.id),
palette = GetPedPaletteVariation(ped, component.id),
}
elseif component.type == "prop" then
outfitData[component.name] = {
id = component.id,
type = component.type,
propIndex = GetPedPropIndex(ped, component.id),
propTexture = GetPedPropTextureIndex(ped, component.id),
}
end
end
return outfitData
end
local function ApplyPedOutfit(ped, outfitData)
if not outfitData or type(outfitData) ~= "table" then
print("ApplyPedOutfit: Invalid outfitData provided.")
return
end
for componentName, data in pairs(outfitData) do
if data.type == "drawable" then
SetPedComponentVariation(ped, data.id, data.drawable or 0, data.texture or 0, data.palette or 0)
elseif data.type == "prop" then
if data.propIndex == -1 or data.propIndex == nil then
ClearPedProp(ped, data.id)
else
SetPedPropIndex(ped, data.id, data.propIndex, data.propTexture or 0, true)
end
end
end
end
-- Public Interface
function Cutscene.GetTags(cutscene)
return GetCutsceneTags(cutscene)
end
function Cutscene.Load(cutscene)
return LoadCutscene(cutscene)
end
function Cutscene.SavePedOutfit(ped)
return SavePedOutfit(ped)
end
function Cutscene.ApplyPedOutfit(ped, outfitData)
return ApplyPedOutfit(ped, outfitData)
end
function Cutscene.Create(cutscene, coords, srcs)
local lastCoords = coords or GetEntityCoords(PlayerPedId())
DoScreenFadeOut(0)
local tagsFromCutscene = GetCutsceneTags(cutscene)
if not LoadCutscene(cutscene) then
print("Cutscene.Create: Failed to load cutscene", cutscene)
DoScreenFadeIn(0)
return false
end
srcs = srcs or {}
local clothes = {}
local localped = PlayerPedId()
-- Process players and create necessary peds
local playersToProcess = { { ped = localped, identifier = "localplayer", coords = lastCoords } }
for _, src_raw in ipairs(srcs) do
if type(src_raw) == 'number' then
if src_raw and not DoesEntityExist(src_raw) then
local playerPed = GetPlayerPed(GetPlayerFromServerId(src_raw))
if DoesEntityExist(playerPed) then
local ped = ClonePed(playerPed, false, false, true)
table.insert(playersToProcess, { ped = ped, identifier = "player" })
end
else
table.insert(playersToProcess, { ped = src_raw, identifier = "user" })
end
elseif type(src_raw) == 'string' then
local ped = CreatePedFromModel(src_raw, GetEntityCoords(localped))
if ped then
table.insert(playersToProcess, { ped = ped, identifier = 'script' })
end
end
end
-- Process available tags and assign to players
local availableTags = table.shallow_copy(tagsFromCutscene or {})
local usedTags = {}
local cleanupTags = {}
for _, playerData in ipairs(playersToProcess) do
local currentPed = playerData.ped
if not currentPed or not DoesEntityExist(currentPed) then goto continue end
local tagTable = table.remove(availableTags, 1)
if not tagTable then
print("Cutscene.Create: No available tags for player", playerData.identifier)
break
end
local isPedMale = IsPedMale(currentPed)
local tag = isPedMale and tagTable.male or tagTable.female
local unusedTag = not isPedMale and tagTable.male or tagTable.female -- needs to be this way as default has to be null for missing female
SetCutsceneEntityStreamingFlags(tag, 0, 1)
RegisterEntityForCutscene(currentPed, tag, 0, GetEntityModel(currentPed), 64)
SetCutscenePedComponentVariationFromPed(tag, currentPed, 0)
clothes[tag] = {
clothing = SavePedOutfit(currentPed),
ped = currentPed
}
table.insert(usedTags, tag)
if unusedTag then table.insert(cleanupTags, unusedTag) end
::continue::
end
-- Clean up unused tags
for _, tag in ipairs(cleanupTags) do
local ped = RegisterEntityForCutscene(0, tag, 3, 0, 64)
if ped then
SetEntityVisible(ped, false, false)
end
end
-- Handle remaining unused tags
for _, tag in ipairs(availableTags) do
for _, tagType in pairs({ tag.male, tag.female }) do
if tagType then
local ped = RegisterEntityForCutscene(0, tagType, 3, 0, 64)
if ped then
SetEntityVisible(ped, false, false)
end
end
end
end
return {
cutscene = cutscene,
coords = coords,
tags = usedTags,
srcs = srcs,
peds = playersToProcess,
clothes = clothes,
}
end
function Cutscene.Start(cutsceneData)
if not cutsceneData then
print("Cutscene.Start: Cutscene data is nil.")
return
end
DoScreenFadeIn(FADE_DURATION)
Cutscene.done = false
local clothes = cutsceneData.clothes
local coords = cutsceneData.coords
-- Start cutscene
if coords then
if type(coords) == 'boolean' then
coords = GetEntityCoords(PlayerPedId())
end
StartCutsceneAtCoords(coords.x, coords.y, coords.z, 0)
else
StartCutscene(0)
end
Wait(100)
-- Apply clothing to cutscene characters
for k, datam in pairs(clothes) do
local ped = datam.ped
if DoesEntityExist(ped) then
SetCutscenePedComponentVariationFromPed(k, ped, 0)
ApplyPedOutfit(ped, datam.clothing)
end
end
-- Scene loading thread
CreateThread(function()
local lastCoords
while not Cutscene.done do
local coords = GetWorldCoordFromScreenCoord(0.5, 0.5)
if not lastCoords or #(lastCoords - coords) > 100 then
NewLoadSceneStartSphere(coords.x, coords.y, coords.z, 2000, 0)
lastCoords = coords
end
Wait(500)
end
end)
-- Control blocking thread
CreateThread(function()
while not Cutscene.done do
DisableAllControlActions(0)
DisableFrontendThisFrame()
Wait(3)
end
end)
-- Main cutscene loop
while not HasCutsceneFinished() and not Cutscene.done do
Wait(0)
if IsDisabledControlJustPressed(0, 200) then
DoScreenFadeOut(FADE_DURATION)
Wait(FADE_DURATION)
StopCutsceneImmediately()
Wait(500)
Cutscene.done = true
break
end
end
-- Cleanup
DoScreenFadeIn(FADE_DURATION)
for _, playerData in ipairs(cutsceneData.peds) do
local ped = playerData.ped
if not ped or not DoesEntityExist(ped) then goto continue end
if playerData.identifier == 'script' then
DeleteEntity(ped)
elseif playerData.identifier == 'localplayer' then
SetEntityCoords(ped, playerData.coords.x, playerData.coords.y, playerData.coords.z, false, false, false, false)
end
::continue::
end
Cutscene.done = true
end
-- RegisterCommand('cutscene', function(source, args, rawCommand)
-- local cutscene = args[1]
-- if cutscene then
-- local cutsceneData = Cutscene.Create(cutscene, false, { 1,1,1 })
-- Cutscene.Start(cutsceneData)
-- end
-- end, false)
return Cutscene
+3 -2
View File
@@ -129,7 +129,7 @@ end
--- @param entityData EntityData
--- @return table Registered point/entity entry (the value stored in ClientEntity.All[entityData.id]).
function ClientEntity.Create(entityData)
entityData.id = entityData.id or Ids.CreateUniqueId(ClientEntity.All)
entityData.id = entityData.id or lib.string.random('Aa1A', 8) -- Generate a random ID if not provided
if ClientEntity.All[entityData.id] then return ClientEntity.All[entityData.id] end
entityData.rotation = entityData.rotation or vector3(0.0, 0.0, entityData.heading or 0.0)
entityData.invoked = entityData.invoked or GetInvokingResource() or "community_bridge"
@@ -236,7 +236,8 @@ function ClientEntity.SetAnim(id, anim)
local entity = entityData.spawned
if not entity or not DoesEntityExist(entity) then return end
if not anim then return Bridge.Anim.Stop(id) end
Bridge.Anim.Play(id, entity, anim.dict, anim.name, anim.blendIn or 8.0, anim.blendOut or -8.0, anim.duration, anim.flags, anim.playbackRate or 0.0, anim.onComplete)
lib.playAnim(entity, anim.dict, anim.name, anim.blendIn or 8.0, anim.blendOut or -8.0, anim.duration, anim.flags, anim.playbackRate or 0.0)
end
--- Attaches the spawned FiveM entity for a ClientEntity to a target, or detaches when nil.
+2 -2
View File
@@ -14,7 +14,7 @@ local Invoked = {}
function ServerEntity.New(id, entityType, model, coords, rotation, args)
assert(coords, "Coords are required for entity creation")
local self = args or {}
self.id = id or Ids.CreateUniqueId(Entities)
self.id = id or lib.string.random('Aa1A', 8) -- Generate a random ID if not provided
self.entityType = entityType
self.model = model
self.coords = coords
@@ -37,7 +37,7 @@ end
function ServerEntity.CreateBulk(entities)
local createdEntities = {}
for _, entityData in pairs(entities) do
local id = entityData.id or Ids.CreateUniqueId(Entities)
local id = entityData.id or lib.string.random('Aa1A', 8)
local entity = ServerEntity.New(id, entityData.entityType, entityData.model, entityData.coords, entityData.rotation, entityData)
createdEntities[id] = entity
end
+1 -17
View File
@@ -36,11 +36,6 @@ end
cLib = {
Require = Require,
Callback = Callback or Require("lib/callback/shared/callback.lua"),
Ids = Ids or Require("lib/utility/shared/ids.lua"),
Tables = Table or Require("lib/utility/shared/tables.lua"),
Prints = Prints or Require("lib/utility/shared/prints.lua"),
Math = Math or Require("lib/utility/shared/math.lua"),
LA = LA or Require("lib/utility/shared/la.lua")
}
@@ -48,10 +43,7 @@ exports('cLib', cLib)
if not IsDuplicityVersion() then goto client end
cLib.SQL = SQL or Require("lib/sql/server/sqlHandler.lua")
cLib.Logs = Logs or Require("lib/logs/server/logs.lua")
cLib.Marker = Marker or Require("lib/markers/server/server.lua")
cLib.Shell = Shells or Require("lib/shells/server/shells.lua")
cLib.Entity = ServerEntity or Require("lib/entities/server/server_entity.lua")
-- Depricated
@@ -60,19 +52,11 @@ cLib.ServerEntity = cLib.Entity
if IsDuplicityVersion() then return cLib end
::client::
cLib.Scaleform = Scaleform or Require("lib/scaleform/client/scaleform.lua")
cLib.Placeable = Placeable or Require("lib/placers/client/object_placer.lua")
cLib.Utility = Utility or Require("lib/utility/client/utility.lua")
cLib.PlaceableObject = ObjectPlacer or Require("lib/placers/client/placeable_object.lua")
cLib.Raycast = Raycast or Require("lib/raycast/client/raycast.lua")
cLib.PlaceableObject = Require("lib/placers/client/placeable_object.lua")
cLib.Point = Point or Require("lib/points/client/points.lua")
cLib.Particle = Particle or Require("lib/particles/client/particles.lua")
cLib.Marker = Marker or Require("lib/markers/client/markers.lua")
cLib.Anim = Anim or Require("lib/anim/client/client.lua")
cLib.Cutscene = Cutscene or Require("lib/cutscenes/client/cutscene.lua")
cLib.Particle = Particle or Require("lib/particles/client/particles.lua")
cLib.Entity = ClientEntity or Require("lib/entities/client/client_entity.lua")
cLib.Vehicles = Vehicles or Require("lib/vehicles/client.lua")
-- Deprecated
cLib.ClientEntity = cLib.Entity
-147
View File
@@ -1,147 +0,0 @@
---@diagnostic disable: duplicate-set-field
Marker = {}
local Created = setmetatable({}, { __mode = "k" }) --what is mode?
local Ids = Ids or Require("lib/utility/shared/ids.lua")
local point = Point or Require("lib/points/client/points.lua")
local loopRunning = false
local Drawing = {}
--- This will validate the marker data.
--- @param data table{position: vector3, offset: vector3, rotation: vector3, size: vector3, color: vector3, alpha: number, bobUpAndDown: boolean, marker: number, interaction: function}
--- @return boolean
local function validateMarkerData(data)
if not data.position or not data.position.x or not data.position.y or not data.position.z then
print("Invalid marker position. Must be a vector3 with x, y, and z coordinates.")
return false
end
if data.offset and (not data.offset.x or not data.offset.y or not data.offset.z) then
print("Invalid marker offset. Must be a vector3 with x, y, and z coordinates.")
return false
end
if data.rotation and (not data.rotation.x or not data.rotation.y or not data.rotation.z) then
print("Invalid marker rotation. Must be a vector3 with x, y, and z coordinates.")
return false
end
return true
end
--- This will create a marker.
--- @param data table{position: vector3, offset: vector3, rotation: vector3, size: vector3, color: vector3, alpha: number, bobUpAndDown: boolean, marker: number, interaction: function}
--- @return string|nil
function Marker.Create(data)
local _id = data.id or Ids.CreateUniqueId(Created)
if not validateMarkerData(data) then return end
local basePosition = data.position or vector3(0.0, 0.0, 0.0)
local baseOffset = data.offset or vector3(0.0, 0.0, 0.0)
local data = {
id = _id,
position = vector3(basePosition.x + baseOffset.x, basePosition.y + baseOffset.y, basePosition.z + baseOffset.z),
marker = data.marker or 1,
rotation = data.rotation or vector3(0, 0, 0),
size = data.size or vector3(1.0, 1.0, 1.0),
color = data.color or vector3(0, 255, 0),
alpha = data.alpha or 255,
bobUpAndDown = data.bobUpAndDown,
-- interaction = data.interaction or false, -- Uncomment if you re-implement interaction logic
rotate = data.rotate,
textureDict = data.textureDict,
textureName = data.textureName,
drawOnEnts = data.drawOnEnts,
}
Created[_id] = data
point.Register(
_id, data.position, data.drawDistance or 50.0, data,
function(_)
if not Created[_id] then return point.Remove(_id) end
Drawing[_id] = Created[_id]
Marker.Run()
end,
function(markerData)
Drawing[_id] = nil
end, nil
)
return _id
end
--- This will remove a marker.
--- @param id string
--- @return boolean
function Marker.Remove(id)
if not Created[id] then return false end
point.Remove(id)
Drawing[id] = nil
Created[id] = nil
return true
end
--- This will remove all markers.
--- @param id string
function Marker.RemoveAll()
for id, _ in pairs(Created) do
point.Remove(id)
Created[id] = nil
end
end
-- This will loop through all marker(points) in range and draw them.
-- @param data table{marker: number, position: vector3, rotation: vector3, size: vector3, color: vector3, alpha: number, bobUpAndDown: boolean, faceCamera: boolean, rotate: boolean, textureDict: string, textureName: string, drawOnEnts: boolean}
-- @return nil
function Marker.Run()
if loopRunning then return end
loopRunning = true
CreateThread(function()
while loopRunning do
if not next(Created) then
loopRunning = false
return
end
for drawingId, drawingData in pairs(Drawing) do
if not Created[drawingId] then
Drawing[drawingId] = nil
goto continue
end
DrawMarker(
drawingData.marker,
drawingData.position.x, drawingData.position.y, drawingData.position.z,
0.0, 0.0, 0.0,
drawingData.rotation.x, drawingData.rotation.y, drawingData.rotation.z,
drawingData.size.x, drawingData.size.y, drawingData.size.z,
drawingData.color.x, drawingData.color.y, drawingData.color.z, drawingData.alpha,
drawingData.bobUpAndDown, drawingData.faceCamera, false,
drawingData.rotate, drawingData.textureDict, drawingData.textureName, drawingData.drawOnEnts
)
::continue::
end
Wait(2)
end
end)
end
RegisterNetEvent("community_bridge:Client:Marker", function(data)
Marker.Create(data)
end)
RegisterNetEvent("community_bridge:Client:MarkerBulk", function(datas)
if not datas then return end
for _, data in pairs(datas) do
Marker.Create(data)
end
end)
RegisterNetEvent("community_bridge:Client:MarkerRemove", function(id)
Marker.Remove(id)
end)
RegisterNetEvent("community_bridge:Client:MarkerRemoveBulk", function(ids)
if not ids then return end
for _, id in pairs(ids) do
Marker.Remove(id)
end
end)
exports("Marker", Marker)
return Marker
-75
View File
@@ -1,75 +0,0 @@
---@diagnostic disable: duplicate-set-field
local id = Ids or Require("lib/utility/shared/ids.lua")
Marker = {}
local Created = {}
function Marker.New(data)
if not data.position or not data.position.x or not data.position.y or not data.position.z then
print("Invalid marker position. Must be a vector3 with x, y, and z coordinates.")
return
end
local _id = data.id or id.CreateUniqueId(Created)
local data = {
id = _id,
position = data.position,
offset = data.offset or vector3(0.0, 0.0, 0.0),
marker = data.marker or 1,
rotation = data.rotation or vector3(0, 0, 0),
size = data.size or vector3(1.0, 1.0, 1.0),
color = data.color or vector3(0, 255, 0),
alpha = data.alpha or 255,
bobUpAndDown = data.bobUpAndDown,
-- interaction = data.interaction or false, -- Uncomment if you re-implement interaction logic
rotate = data.rotate,
textureDict = data.textureDict,
textureName = data.textureName,
drawOnEnts = data.drawOnEnts,
}
Created[_id] = data
return _id
end
function Marker.Destroy(id)
if not id or not Created[id] then return end
Created[id] = nil
return true
end
function Marker.Create(data)
local _id = Marker.New(data)
if not _id then return end
TriggerClientEvent("community_bridge:Client:Marker", -1, Created[_id])
return _id
end
function Marker.Remove(id)
if not Marker.Destroy(id) then return end
TriggerClientEvent("community_bridge:Client:MarkerRemove", -1, id)
end
function Marker.CreateBulk(datas)
if not datas then return end
local toClient = {}
for k, v in pairs(datas) do
table.insert(toClient, Marker.Create(v))
end
TriggerClientEvent("community_bridge:Client:MarkerBulk", -1, toClient)
return toClient
end
function Marker.RemoveBulk(ids)
if not ids then return end
local toClient = {}
for k, v in pairs(ids) do
local id = v
if type(v) == "table" then
id = v.id
end
Marker.Destroy(id)
table.insert(toClient, id)
end
TriggerClientEvent("community_bridge:Client:MarkerRemoveBulk", -1, toClient)
end
exports("Marker", Marker)
return Marker
-131
View File
@@ -1,131 +0,0 @@
Particles = {}
Particle = {}
---@diagnostic disable: duplicate-set-field
Ids = Ids or Require("lib/utility/shared/ids.lua")
---Loads a ptfx asset into memory.
---@param dict string
---@return boolean
function LoadPtfxAsset(dict)
local failed = 100
while not HasNamedPtfxAssetLoaded(dict) and failed >= 0 do
RequestNamedPtfxAsset(dict)
failed = failed - 1
Wait(100)
end
assert(failed > 0, "Failed to load dict asset: " .. dict)
return HasNamedPtfxAssetLoaded(dict)
end
--- Create a particle effect at the specified position and rotation.
--- @param dict string
--- @param ptfx string
--- @param pos vector3
--- @param rot vector3
--- @param scale number
--- @param color vector3
--- @param looped boolean
--- @param removeAfter number|nil
--- @return number|nil ptfxHandle -- The handle of the particle effect, or nil if it failed to create.
function Particle.Play(dict, ptfx, pos, rot, scale, color, looped, removeAfter)
LoadPtfxAsset(dict)
UseParticleFxAssetNextCall(dict)
SetParticleFxNonLoopedColour(color.x, color.y, color.z)
local particle = nil
removeAfter = removeAfter or 5000
if looped then
particle = StartParticleFxLoopedAtCoord(ptfx, pos.x, pos.y, pos.z, rot.x, rot.y, rot.z, scale, false, false, false, false)
local strParticle = tostring(particle)
Particles[strParticle] = particle
Wait(10)
if particle == 0 or not DoesParticleFxLoopedExist(particle) then
particle = StartParticleFxNonLoopedAtCoord(ptfx, pos.x, pos.y, pos.z, rot.x, rot.y, rot.z, scale, false, false, false, false)
if not particle and particle == 0 then
print(string.format("[Particle] Failed to start particle fx: %s from dict: %s", ptfx, dict))
return nil
end
local strParticle = tostring(particle)
Particles[strParticle] = particle
CreateThread(function()
while Particles[strParticle] do
Wait(removeAfter)
if not Particles[strParticle] then break end
RemoveParticleFx(particle, false)
particle = StartParticleFxNonLoopedAtCoord(ptfx, pos.x, pos.y, pos.z, rot.x, rot.y, rot.z, scale, false, false, false, false)
Particles[strParticle] = particle
end
end)
return strParticle
else
if not removeAfter or removeAfter <= 0 then return particle end
CreateThread(function()
while Particles[strParticle] do
Wait(removeAfter)
if not Particles[strParticle] then break end
StopParticleFxLooped(particle, false)
UseParticleFxAssetNextCall(dict)
LoadPtfxAsset(dict)
particle = StartParticleFxLoopedAtCoord(ptfx, pos.x, pos.y, pos.z, rot.x, rot.y, rot.z, scale, false, false, false, false)
Particles[strParticle] = particle
end
end)
return strParticle
end
else
particle = StartParticleFxLoopedAtCoord(ptfx, pos.x, pos.y, pos.z, rot.x, rot.y, rot.z, scale, false, false, false, false)
Wait(10)
if not DoesParticleFxLoopedExist(particle) then
particle = StartParticleFxNonLoopedAtCoord(ptfx, pos.x, pos.y, pos.z, rot.x, rot.y, rot.z, scale, false, false, false, false)
end
Wait(removeAfter)
Particle.Stop(particle)
end
return particle
end
function Particle.Stop(particle)
if not particle then return end
StopParticleFxLooped(particle, false)
RemoveParticleFx(particle, false)
RemoveNamedPtfxAsset(particle)
Particles[tostring(particle)] = nil
end
function Particle.CreateOnEntity(dict, ptfx, entity, offset, rot, scale, color, looped, loopLength)
LoadPtfxAsset(dict)
UseParticleFxAssetNextCall(dict)
SetParticleFxNonLoopedColour(color.x, color.y, color.z)
local particle = nil
if looped then
particle = StartNetworkedParticleFxLoopedOnEntity(ptfx, entity, offset.x, offset.y, offset.z, rot.x, rot.y, rot.z, scale, false, false, false)
if loopLength then
Wait(loopLength)
RemoveParticleFxFromEntity(entity)
end
else
particle = StartNetworkedParticleFxLoopedOnEntity(ptfx, entity, offset.x, offset.y, offset.z, rot.x, rot.y, rot.z, scale, false, false, false)
end
RemoveNamedPtfxAsset(ptfx)
return particle
end
function Particle.CreateOnEntityBone(dict, ptfx, entity, bone, offset, rot, scale, color, looped, loopLength)
LoadPtfxAsset(dict)
UseParticleFxAssetNextCall(dict)
SetParticleFxNonLoopedColour(color.x, color.y, color.z)
local particle = nil
if looped then
particle = StartNetworkedParticleFxLoopedOnEntityBone(ptfx, entity, offset.x, offset.y, offset.z, rot.x, rot.y, rot.z, bone, scale, false, false, false)
if loopLength then
Wait(loopLength)
RemoveParticleFxFromEntity(entity)
end
else
particle = StartNetworkedParticleFxNonLoopedOnEntityBone(ptfx, entity, offset.x, offset.y, offset.z, rot.x, rot.y, rot.z, bone, scale, false, false, false)
end
RemoveNamedPtfxAsset(ptfx)
return particle
end
return Particle
-53
View File
@@ -1,53 +0,0 @@
Raycast = {}
--Rework of oxs Raycast system
function Raycast.GetForwardVector(rotation)
local camRot = rotation or GetFinalRenderedCamRot(2)
-- Convert each component to radians
local rx = math.rad(camRot.x)
local ry = math.rad(camRot.y)
local rz = math.rad(camRot.z)
-- Calculate sin and cos for each axis
local sx = math.sin(rx)
local cx = math.cos(rx)
local sy = math.sin(ry)
local cy = math.cos(ry)
local sz = math.sin(rz)
local cz = math.cos(rz)
-- Create forward vector components
local x = -sz * math.abs(cx)
local y = cz * math.abs(cx)
local z = sx
return vector3(x, y, z)
end
function Raycast.ToCoords(startCoords, endCoords, flag, ignore)
local probe = StartShapeTestLosProbe(startCoords.x, startCoords.y, startCoords.z, endCoords.x, endCoords.y, endCoords.z, flag or 511, PlayerPedId(), ignore or 4)
local retval, entity, finalCoords, normals, material = 1, nil, nil, nil, nil
local timeout = 500
while retval == 1 and timeout > 0 do
retval, entity, finalCoords, normals, material = GetShapeTestResultIncludingMaterial(probe)
timeout = timeout - 1
Wait(0)
end
return retval, entity, finalCoords, normals, material
end
function Raycast.FromCamera(flags, ignore, distance)
local coords = GetFinalRenderedCamCoord()
distance = distance or 10
local destination = coords + Raycast.GetForwardVector() * distance
local retval, entity, finalCoords, normals, material = Raycast.ToCoords(coords, destination, flags, ignore)
if retval ~= 1 then
local newDest = destination - vector3(0, 0, 10)
return Raycast.ToCoords(destination, newDest, flags, ignore)
end
return retval, entity, finalCoords, normals, material
end
return Raycast
-129
View File
@@ -1,129 +0,0 @@
---@class Scaleform
local Scaleform = {}
-- Constants
local SCALEFORM_TIMEOUT = 5000
local BACKGROUND_COLOR_VALUE = 80
local CONTROL_TYPE = 2
local RENDER_WAIT_TIME = 2
-- Local utility functions
local function setupButton(scaleform, button)
PushScaleformMovieFunction(scaleform, button.type)
if button.int then
PushScaleformMovieFunctionParameterInt(button.int)
end
-- Handle key index setup
if button.keyIndex then
if type(button.keyIndex) == "table" then
for _, keyCode in pairs(button.keyIndex) do
N_0xe83a3e3557a56640(GetControlInstructionalButton(CONTROL_TYPE, keyCode, true))
end
else
ScaleformMovieMethodAddParamPlayerNameString(GetControlInstructionalButton(CONTROL_TYPE, button.keyIndex[1], true))
end
end
-- Handle button name setup
if button.name then
BeginTextCommandScaleformString("STRING")
AddTextComponentScaleform(button.name)
EndTextCommandScaleformString()
end
-- Handle background color
if button.type == 'SET_BACKGROUND_COLOUR' then
for _ = 1, 4 do
PushScaleformMovieFunctionParameterInt(BACKGROUND_COLOR_VALUE)
end
end
PopScaleformMovieFunctionVoid()
end
---Creates and sets up a scaleform movie
---@param scaleformName string The name of the scaleform to load
---@param buttons table Array of button configurations
---@return number scaleform The loaded scaleform handle
local function setupScaleform(scaleformName, buttons)
local scaleform = RequestScaleformMovie(scaleformName)
local timeout = SCALEFORM_TIMEOUT
-- Wait for scaleform to load
while not HasScaleformMovieLoaded(scaleform) and timeout > 0 do
timeout = timeout - 1
Wait(0)
end
if timeout <= 0 then
error('Scaleform failed to load: ' .. scaleformName)
end
DrawScaleformMovieFullscreen(scaleform, 255, 255, 255, 0, 0)
-- Setup each button
for _, button in ipairs(buttons) do
setupButton(scaleform, button)
end
return scaleform
end
---Sets up instructional buttons with default configuration
---@param buttons table Optional custom button configuration
---@return number scaleform The configured instructional buttons scaleform
function Scaleform.SetupInstructionalButtons(buttons)
buttons = buttons or {
-- Default button configuration commented out
-- Uncomment and modify as needed
-- {type = "CLEAR_ALL"},
-- {type = "SET_CLEAR_SPACE", int = 200},
-- {type = "SET_DATA_SLOT", name = config?.place_object?.name or 'Place Object:', keyIndex = config?.place_object?.key or {223}, int = 5},
-- {type = "SET_DATA_SLOT", name = config?.cancel_placement?.name or 'Cancel Placement:', keyIndex = config?.cancel_placement?.key or {222}, int = 4},
-- {type = "SET_DATA_SLOT", name = config?.snap_to_ground?.name or 'Snap to Ground:', keyIndex = config?.snap_to_ground?.key or {19}, int = 1},
-- {type = "SET_DATA_SLOT", name = config?.rotate?.name or 'Rotate:', keyIndex = config?.rotate?.key or {14, 15}, int = 2},
-- {type = "SET_DATA_SLOT", name = config?.distance?.name or 'Distance:', keyIndex = config?.distance?.key or {14,15,36}, int = 3},
-- {type = "SET_DATA_SLOT", name = config?.toggle_placement?.name or 'Toggle Placement:', keyIndex = config?.toggle_placement?.key or {199}, int = 0},
-- {type = "DRAW_INSTRUCTIONAL_BUTTONS"},
-- {type = "SET_BACKGROUND_COLOUR"},
}
return setupScaleform("instructional_buttons", buttons)
end
-- Active scaleform tracking
local activeScaleform = nil
---Runs a scaleform with optional update callback
---@param scaleform number The scaleform handle to run
---@param onUpdate function Optional callback for updates during runtime
function Scaleform.Run(scaleform, onUpdate)
if activeScaleform then return end
activeScaleform = scaleform
CreateThread(function()
while activeScaleform do
DrawScaleformMovieFullscreen(scaleform, 255, 255, 255, 255, 0)
if onUpdate then
local shouldStop = onUpdate()
if shouldStop then
Scaleform.Stop()
break
end
end
Wait(RENDER_WAIT_TIME)
end
end)
end
---Stops the currently running scaleform
function Scaleform.Stop()
activeScaleform = nil
end
exports("Scaleform", Scaleform)
return Scaleform
-53
View File
@@ -1,53 +0,0 @@
Shells = Shells or {}
--Data table
Shells.Targets = Shells.Targets or {
['entrance'] = {
['enter'] = {
label = 'Enter',
icon = 'fa-solid fa-door-open',
onSelect = function(entity, shellId, objectId)
TriggerServerEvent('community_bridge:server:EnterShell', shellId, objectId)
end
},
},
['exit'] = {
['leave'] = {
label = 'Exit',
icon = 'fa-solid fa-door-closed',
onSelect = function(entity, shellId, objectId)
TriggerServerEvent('community_bridge:server:ExitShell', shellId, objectId)
end
}
}
}
--Functions to set data table
Shells.Target = {
Set = function(shellType, options)
assert(shellType, "Shells.Target.Set: 'shellType' is required")
options = options or {}
for key, value in pairs(options) do
if Shells.Targets[shellType] and Shells.Targets[shellType][key] then
value.onSelect = Shells.Targets[shellType][key].onSelect
end
Shells.Targets[shellType] = Shells.Targets[shellType] or {}
Shells.Targets[shellType][key] = value
end
return true
end,
Get = function(shellType, shellId, objectId)
local aOptions = {}
for key, value in pairs(Shells.Targets[shellType] or {}) do
local onSelect = value.onSelect
value.onSelect = function(entity)
onSelect(entity, shellId, objectId)
end
table.insert(aOptions, value)
end
return aOptions
end
}
return Shells
-269
View File
@@ -1,269 +0,0 @@
local Target = Require('modules/target/_default/init.lua')
local ClientEntity = Require("lib/entities/client/client_entity.lua")
Shells = Shells or Require("lib/shells/client/config.lua")
Shells.All = Shells.All or {}
local insideShell = false
Shells.Events = {
OnSpawn = {},
OnRemove = {},
}
--Set Target lang or additionals
-- Shells.Target.Set('entrance', {
-- enter = {
-- label = 'yerp',
-- icon = 'fa-solid fa-door-open',
-- },
-- })
-- Shells.Target.Set('exit', {
-- leave = {
-- label = 'leerp',
-- icon = 'fa-solid fa-door-closed',
-- },
-- })
Shells.Event = {
Add = function(eventName, callback)
if Shells.Events[eventName] then
table.insert(Shells.Events[eventName], callback)
else
print(string.format("Shells.Event.Add: Invalid event name '%s'", eventName))
end
end,
Trigger = function(eventName, ...)
if Shells.Events[eventName] then
for _, callback in ipairs(Shells.Events[eventName]) do
callback(...)
end
else
print(string.format("Shells.Event.Trigger: Invalid event name '%s'", eventName))
end
end,
}
-- Shells.Event.Add('OnSpawn', function(pointData, entity)
-- print(string.format("Exterior point created with ID: %s, Type: %s, Entity: %s", pointData.id, pointData.type, entity))
-- end)
-- Shells.Event.Add('OnRemove', function(pointData)
-- print(string.format("Interior point created with ID: %s, Type: %s", pointData.id, pointData.type))
-- end)
function Shells.AddInteriorObject(shell, objectData)
objectData.OnSpawn = function(pointData)
Shells.Event.Trigger('OnSpawn', objectData, pointData.spawned)
local targetOptions = Shells.Target.Get(objectData.type, shell.id, objectData.id)
if targetOptions then
local size = vector3(objectData.distance / 2, objectData.distance / 2, objectData.distance / 2) -- this might need to be size
Target.AddBoxZone(objectData.id, objectData.coords, size, objectData.rotation.z, targetOptions, true)
end
end
objectData.OnRemove = function(pointData)
Shells.Event.Trigger('OnRemove', objectData, pointData.spawned)
Target.RemoveZone(objectData.id)
end
return ClientEntity.Register(objectData)
end
function Shells.SetupInterior(shell)
if not shell or not shell.interior then return end
for _, v in pairs(shell.interior) do
local pointData = Shells.AddInteriorObject(shell, v)
shell.interiorSpawned[pointData.id] = pointData
end
end
function Shells.SetupExterior(shell)
if not shell or not shell.exterior then return end
for k, v in pairs(shell.exterior) do
local pointData = Shells.AddInteriorObject(shell, v)
shell.exteriorSpawned[pointData.id] = pointData
end
end
function Shells.ClearInterior(shell)
if not shell or not shell.interiorSpawned then return end
for _, v in pairs(shell.interiorSpawned) do
ClientEntity.Unregister(v.id)
Target.RemoveZone(v.id)
end
shell.interiorSpawned = {}
end
function Shells.ClearExterior(shell)
if not shell or not shell.exteriorSpawned then return end
for _, v in pairs(shell.exteriorSpawned) do
ClientEntity.Unregister(v.id)
Target.RemoveZone(v.id)
end
shell.exteriorSpawned = {}
end
function Shells.New(data)
assert(data.id, "Shells.Create: 'id' is required")
assert(data.model, "Shells.Create: 'shellModel' is required")
assert(data.coords, "Shells.Create: 'coords' is required")
local exterior = data.exterior or {}
local exteriorSpawned = {}
for k, v in pairs(exterior or {}) do
v.OnSpawn = function(pointData)
Shells.Event.Trigger('OnSpawn', v, pointData.spawned)
local targetOptions = Shells.Target.Get(v.type, data.id, v.id)
if targetOptions then
local size = vector3(v.distance / 2, v.distance / 2, v.distance / 2)
Target.AddBoxZone(v.id, v.coords, size, v.rotation.z, targetOptions, true)
end
end
v.OnRemove = function(pointData)
Shells.Event.Trigger('OnRemove', v, pointData.spawned)
Target.RemoveZone(v.id)
end
local pointData = ClientEntity.Register(v)
exteriorSpawned[pointData.id] = pointData
end
data.interiorSpawned = {}
data.exteriorSpawned = exteriorSpawned
Shells.All[data.id] = data
return data
end
local returnPoint = nil
function Shells.Enter(id, entranceId)
local shell = Shells.All[id]
if not shell then
print(string.format("Shells.Spawn: Shell with ID '%s' not found", id))
return
end
local entrance = shell.interior[entranceId]
if not entrance then
print(string.format("Shells.Enter: Entrance with ID '%s' not found in shell '%s'", entranceId, id))
return
end
local ped = PlayerPedId()
returnPoint = GetEntityCoords(ped)
DoScreenFadeOut(1000)
Wait(1000)
local entranceCoords = entrance.coords
SetEntityCoords(ped, entranceCoords.x, entranceCoords.y, entranceCoords.z, false, false, false, true)
FreezeEntityPosition(ped, true)
local oldShell = insideShell and Shells.All[insideShell]
if oldShell?.id ~= id then
Shells.ClearExterior(oldShell)
Shells.ClearInterior(oldShell)
end
Shells.ClearExterior(shell)
Shells.SetupInterior(shell)
ClientEntity.Register(shell)
Wait(1000) -- Wait for the fade out to complete
FreezeEntityPosition(ped, false)
DoScreenFadeIn(1000)
insideShell = shell.id
end
function Shells.Exit(id, exitId)
local shell = Shells.All[id]
if not shell then
print(string.format("Shells.Exit: Shell with ID '%s' not found", id))
return
end
local oldCoords = GetEntityCoords(PlayerPedId())
local oldPoint = shell.exterior[exitId]
if not oldPoint then
print(string.format("Shells.Exit: Old point with ID '%s' not found in shell '%s'", exitId, id))
return
end
DoScreenFadeOut(1000)
Wait(1000)
SetEntityCoords(PlayerPedId(), oldPoint.coords.x, oldPoint.coords.y, oldPoint.coords.z, false, false, false, true)
FreezeEntityPosition(PlayerPedId(), true)
Shells.ClearInterior(shell)
ClientEntity.Unregister(shell.id)
Shells.SetupExterior(shell)
shell.interiorSpawned = {}
FreezeEntityPosition(PlayerPedId(), false)
DoScreenFadeIn(1000)
insideShell = false
end
function Shells.Inside()
return insideShell
end
RegisterNetEvent('community_bridge:client:CreateShell', function(shell)
Shells.New(shell)
end)
RegisterNetEvent('community_bridge:client:EnterShell', function(shellId, entranceId, oldId)
local shell = Shells.All[shellId]
if not shell then
print(string.format("Shells.EnterShell: Shell with ID '%s' not found", shellId))
return
end
Shells.Enter(shellId, entranceId, oldId)
end)
RegisterNetEvent('community_bridge:client:ExitShell', function(shellId, oldId)
local shell = Shells.All[shellId]
print(string.format("Shells.ExitShell: Exiting shell '%s'", shellId))
if not shell then
print(string.format("Shells.ExitShell: Shell with ID '%s' not found", shellId))
return
end
Shells.Exit(shellId, oldId)
end)
RegisterNetEvent('community_bridge:client:AddObjectsToShell', function (shellId, interiorObjects, exteriorObjects)
local shell = Shells.All[shellId]
print(string.format("Shells.AddObjectsToShell: Adding objects to shell '%s'", shellId),
json.encode({interiorObjects = interiorObjects, exteriorObjects = exteriorObjects}, { indent = true }))
if not shell then
print(string.format("Shells.AddObjectsToShell: Shell with ID '%s' not found", shellId))
return
end
local insideShell = Shells.Inside()
if interiorObjects then
for _, obj in pairs(interiorObjects) do
if not shell.interior[obj.id] then
shell.interior[obj.id] = obj
if insideShell and insideShell == shellId then
local pointData = Shells.AddInteriorObject(shell, obj)
shell.interiorSpawned[pointData.id] = pointData
end
end
end
end
if exteriorObjects then
for _, obj in pairs(exteriorObjects) do
if not shell.exterior[obj.id] then
shell.exterior[obj.id] = obj
if not insideShell then
local pointData = Shells.AddInteriorObject(shell, obj)
shell.exteriorSpawned[pointData.id] = pointData
end
end
end
end
end)
RegisterNetEvent('community_bridge:client:CreateShells', function(shells)
print("Shells.CreateShells: Creating shells")
for _, shell in pairs(shells) do
Shells.New(shell)
end
end)
-- TriggerClientEvent('community_bridge:client:CreateShells', -1, toClient)
-- TriggerClientEvent('community_bridge:client:ExitShell', src, oldId)
AddEventHandler('onResourceStart', function(resource)
if resource == GetCurrentResourceName() then
DoScreenFadeIn(1000) -- Fade in when resource stops
if not returnPoint then return end
SetEntityCoords(PlayerPedId(), returnPoint.x, returnPoint.y, returnPoint.z, false, false, false, true)
end
end)
-379
View File
@@ -1,379 +0,0 @@
Ids = Ids or Require("lib/utility/shared/ids.lua")
Shells = Shells or {}
Shells.All = Shells.All or {}
Shells.ActivePlayers = Shells.ActivePlayers or {} -- Track players in shells
Shells.Interactable = Shells.Interactable or {}
Shells.BucketsInUse = Shells.BucketsInUse or {} -- Track buckets in use
function Shells.Interactable.New(_type, id, model, coords, rotation, entityType, distance, meta)
assert(_type, "Shells.Interactable.Create: 'type' is required")
assert(id, "Shells.Interactable.Create: 'name' is required")
assert(coords, "Shells.Interactable.Create: 'coords' is required")
return {
type = _type,
id = id,
model = model,
coords = coords,
rotation = rotation or vector3(0.0, 0.0, 0.0),
distance = distance or 2.0,
entityType = entityType or "object", -- Default entity type
meta = meta or {},
}
end
function Shells.New(data)
local id = data.id or Ids.CreateUniqueId(Shells.All)
local _type = data.type or "none"
local model = data.model
local size = data.size or vector3(10.0, 10.0, 10.0) -- Default size if not provided
local coords = data.coords or vector3(0.0, 0.0, 0.0) -- Default coordinates if not provided
local rotation = data.rotation or vector3(0.0, 0.0, 0.0) -- Default rotation if not provided
local interior = data.interior or {}
local exterior = data.exterior or {}
local bucket = data.bucket or Ids.RandomNumber(Shells.BucketsInUse, 4)
assert(id, "Shells.Create: 'id' is required")
assert(model, "Shells.Create: 'shellModel' is required")
assert(coords, "Shells.Create: 'coords' is required")
local interiorInteractions = {}
for k, v in pairs(interior or {}) do
local interiorCoords = coords + (v.offset or vector3(0.0, 0.0, 0.0))
local interaction = Shells.Interactable.New(
v.type or "none",
v.id or Ids.CreateUniqueId(interiorInteractions),
v.model,
interiorCoords,
v.rotation or vector3(0.0, 0.0, 0.0),
v.entityType or "object", -- Default entity type for interior interactions
v.distance or 2.0,
v.meta
)
interiorInteractions[interaction.id] = interaction
end
local exteriorInteractions = {}
for k, v in pairs(exterior or {}) do
local interaction = Shells.Interactable.New(
v.type or "none",
v.id or Ids.CreateUniqueId(exteriorInteractions),
v.model,
v.coords,
v.rotation or vector3(0.0, 0.0, 0.0),
v.entityType or "object", -- Default entity type for exterior interactions
v.distance or 2.0,
v.meta
)
exteriorInteractions[interaction.id] = interaction
end
local shellData = {
id = id,
type = _type,
entityType = "object", -- Default entity type for shells
model = model,
coords = coords,
size = size or vector3(10.0, 10.0, 10.0), -- Default size if not provided
rotation = rotation or vector3(0.0, 0.0, 0.0),
interior = interiorInteractions,
exterior = exteriorInteractions,
}
Shells.All[id] = shellData
return shellData
end
function Shells.Create(data)
local shell = Shells.New(data)
assert(shell, "Shells.Create: 'shell' is required")
TriggerClientEvent('community_bridge:client:CreateShell', -1, shell)
return shell
end
function Shells.CreateBulk(shells)
assert(shells, "Shells.CreateBulk: 'shells' is required")
assert(type(shells) == "table", "Shells.CreateBulk: 'shells' must be a table")
local toClient = {}
for _, shellData in pairs(shells) do
local shell = Shells.New(shellData)
toClient[shell.id] = shell
end
TriggerClientEvent('community_bridge:client:CreateShells', -1, toClient)
end
function Shells.Enter(src, shellId, entranceId)
src = tonumber(src)
assert(src, "Shells.EnterShell: 'src' is required")
assert(shellId, "Shells.EnterShell: 'shellId' is required")
print(shellId)
local shell = Shells.All[shellId]
assert(shell, "Shell not found: " .. tostring(shellId))
if shell.onEnter then
local canEnter = shell.onEnter(src, shellId)
if not canEnter then return false end
end
if not shell.bucket then
local randNum = Ids.RandomNumber(Shells.BucketsInUse, 4)
shell.bucket = tonumber(randNum)
Shells.BucketsInUse[tostring(randNum)] = true
end
print(shell.bucket)
SetPlayerRoutingBucket(src, shell.bucket)
local exit = shell.exterior[entranceId]?.meta?.link
TriggerClientEvent('community_bridge:client:EnterShell', src, shellId, exit, Shells.ActivePlayers[tostring(src)])
Shells.ActivePlayers[tostring(src)] = shellId
return true
end
function Shells.Exit(src, shellId, oldId)
print(oldId)
src = tonumber(src)
assert(src, "Shells.ExitShell: 'src' is required")
assert(shellId, "Player is not in a shell")
local shell = Shells.All[shellId]
assert(shell, "Shell not found: " .. tostring(shellId))
-- Restore original routing bucket
SetPlayerRoutingBucket(src, 0)
local exit = shell.interior[oldId]?.meta?.link
-- Clear player's shell data
Shells.ActivePlayers[tostring(src)] = nil
if shell.onExit then
shell.onExit(src, shellId)
end
TriggerClientEvent('community_bridge:client:ExitShell', src, shellId, exit)
return true
end
function Shells.Get(shellId)
assert(shellId, "Shells.GetShellById: 'shellId' is required")
return Shells.All[shellId]
end
function Shells.Inside(src)
src = tonumber(src)
assert(src, "Shells.IsInside: 'src' is required")
local shellId = Shells.ActivePlayers[tostring(src)]
if not shellId then
return false
end
local shell = Shells.All[shellId]
if not shell then
return false
end
return shell
end
function Shells.AddObjects(shellId, objects)
assert(shellId, "Shells.AddObjects: 'shellId' is required")
assert(objects, "Shells.AddObjects: 'objects' is required")
assert(type(objects) == "table", "Shells.AddObjects: 'objects' must be a table")
local shell = Shells.All[shellId]
assert(shell, "Shell not found: " .. tostring(shellId))
local interiors = objects.interior or {}
local exteriors = objects.exterior or {}
for _, objData in pairs(interiors) do
local obj = Shells.Interactable.New(
objData.type,
objData.id,
objData.model,
objData.coords,
objData.rotation,
objData.entityType,
objData.distance,
objData.meta
)
shell.interior[obj.id] = obj -- Update the shell's interior with the new object
end
for _, objData in pairs(exteriors) do
local obj = Shells.Interactable.New(
objData.type,
objData.id,
objData.model,
objData.coords,
objData.rotation,
objData.entityType,
objData.distance,
objData.meta
)
shell.exterior[obj.id] = obj -- Update the shell's exterior with the new object
end
TriggerClientEvent('community_bridge:client:AddObjectsToShell', -1, shellId, shell.interior, shell.exterior)
return shell
end
function Shells.RemoveObjects(shellId, objectIds)
assert(shellId, "Shells.RemoveObjects: 'shellId' is required")
assert(objectIds, "Shells.RemoveObjects: 'objects' is required")
if type(objectIds) ~= "table" then
objectIds = {objectIds} -- Ensure it's a table
end
local shell = Shells.All[shellId]
assert(shell, "Shell not found: " .. tostring(shellId))
for _, objId in pairs(objectIds) do
shell.interior[objId] = nil
shell.exterior[objId] = nil
end
TriggerClientEvent('community_bridge:client:RemoveObjectsFromShell', -1, shellId, objectIds)
return shell
end
RegisterNetEvent('community_bridge:server:EnterShell', function(shellId, entranceId)
local src = source
Shells.Enter(src, shellId, entranceId)
end)
RegisterNetEvent('community_bridge:server:ExitShell', function(shellId, oldId)
local src = source
Shells.Exit(src, shellId, oldId)
end)
AddEventHandler('onPlayerJoining', function(playerId)
local src = source
TriggerClientEvent('community_bridge:client:CreateShells', src, Shells.All)
end)
function Shells.GetInteractable(shellId, id)
assert(shellId, "Shells.GetInteractable: 'shellId' is required")
assert(id, "Shells.GetInteractable: 'id' is required")
local shell = Shells.All[shellId]
if not shell then
return nil, "Shell not found: " .. tostring(shellId)
end
local interactable = shell.interior[id] or shell.exterior[id]
if not interactable then
return nil, "Interactable not found: " .. tostring(id)
end
return interactable
end
function Shells.GetClosestInteractable(shellId, coords, exterior)
assert(shellId, "Shells.GetClosestInteriorInteractable: 'shellId' is required")
assert(coords, "Shells.GetClosestInteriorInteractable: 'coords' is required")
local shell = Shells.All[shellId]
if not shell then
return nil, "Shell not found: " .. tostring(shellId)
end
local closest = nil
local closestDistance = math.huge
if exterior then
for _, interactable in pairs(shell.exterior) do
local distance = #(coords - interactable.coords)
if distance < closestDistance then
closestDistance = distance
closest = interactable
end
end
return closest, closestDistance
end
for _, interactable in pairs(shell.interior) do
local distance = #(coords - interactable.coords)
if distance < closestDistance then
closestDistance = distance
closest = interactable
end
end
return closest, closestDistance
end
local testShell = nil
RegisterCommand('shells:create', function(source, args, rawCommand)
local coords = GetEntityCoords(GetPlayerPed(source))
if testShell then
Shells.Exit(source, testShell.id, 'exit1') -- Exit previous shell if it exists
end
testShell = Shells.Create({
id = Ids.CreateUniqueId(Shells.All),
type = "shell",
model = "shell_garagem",
coords = coords + vector3(0.0, 0.0, 100.0), -- Adjusted to place shell slightly below player
rotation = vector3(0.0, 0.0, 0.0),
size = vector3(10.0, 10.0, 10.0),
interior = {
{
id = 'exit1',
type = 'exit',
coords = coords + vector3(0.0, 0.0, 1.0),
rotation = vector3(0.0, 0.0, 0.0),
distance = 2.0,
meta = {
link = 'entrance1',
}
}
},
exterior = {
{
id = 'entrance1',
type = 'entrance',
-- entityType = "object",
-- model = "xm_int_lev_sub_chair_02",
coords = coords - vector3(0.0, 0.0, 0.5),
rotation = vector3(0.0, 0.0, 0.0),
distance = 2.0,
meta = {
link = 'exit1',
}
}
},
})
end, true)
RegisterCommand('shells:addobject', function(source, args, rawCommand)
if not testShell then
print("No shell created. Use /shells:create first.")
return
end
local model = args[1]
if not model then
print("Usage: /shells:addobject <shellId> <model>")
return
end
local shellId = testShell.id
local coords = GetEntityCoords(GetPlayerPed(source))
local objectData = {
type = "none",
entityType = "ped",
id = Ids.CreateUniqueId(Shells.All[shellId].interior),
model = model,
coords = coords - vector3(0.0, 0.0, 0.5), -- Adjusted to place object slightly above player
rotation = vector3(0.0, 0.0, 0.0),
distance = 2.0,
meta = {}
}
Shells.AddObjects(shellId, {interior = {objectData}})
end, true)
AddEventHandler('onResourceStop', function(resource)
if resource == GetCurrentResourceName() then
for src, shellId in pairs(Shells.ActivePlayers) do
SetPlayerRoutingBucket(tonumber(src), 0) -- Reset routing bucket for all players
end
end
end)
AddEventHandler('community_bridge:Server:OnPlayerUnload', function(src)
if not Shells.ActivePlayers[tostring(src)] then return end
print(string.format("Player %d is exiting shell %s", src, Shells.ActivePlayers[tostring(src)]))
Shells.Exit(src, Shells.ActivePlayers[tostring(src)])
Shells.ActivePlayers[tostring(src)] = nil
end)
-139
View File
@@ -1,139 +0,0 @@
--[[
DEPRECATED: the SQL helper module is deprecated in its entirety and will be
REMOVED on 2026-08-22. Migrate to oxmysql directly — MySQL.query.await(query,
params) with ? placeholders — which is safer and more flexible than these
wrappers ever were.
]]
SQL = {}
Require("lib/MySQL.lua", "oxmysql")
local warnedResources = {}
local function warnDeprecated()
local caller = GetInvokingResource() or GetCurrentResourceName()
if warnedResources[caller] then return end
warnedResources[caller] = true
print(("^3[community_bridge] SQL helpers are deprecated and will be REMOVED on 2026-08-22. '%s' should migrate to oxmysql directly (MySQL.query.await with ? placeholders).^0"):format(caller))
end
-- Identifiers (table/column names) cannot be parameterized, so they are
-- validated against a strict pattern and backtick-quoted instead. Values are
-- never concatenated into queries - they always go through ? placeholders.
local function quoteIdentifier(name)
assert(type(name) == "string" and name:match("^[%a_][%w_]*$"),
("SQL: unsafe identifier '%s' - table/column names may only contain letters, digits and underscores"):format(tostring(name)))
return "`" .. name .. "`"
end
--- Builds a parameterized WHERE clause from a table of column = value pairs.
-- Raw WHERE strings are intentionally rejected: they made SQL injection
-- unavoidable whenever a player-influenced value reached these helpers.
local function buildWhere(where)
assert(type(where) == "table" and next(where) ~= nil,
"SQL: where must be a non-empty table of column = value pairs (raw WHERE strings are no longer accepted)")
local conditions = {}
local params = {}
for column, value in pairs(where) do
table.insert(conditions, quoteIdentifier(column) .. " = ?")
table.insert(params, value)
end
return table.concat(conditions, " AND "), params
end
--- Creates a table in the database if it does not exist.
-- @param tableName The name of the table to create. Example: {{ name = "identifier", type = "VARCHAR(50)", primary = true }}
-- @param columns A table containing column definitions, where each column is a table with 'name' and 'type'.
---@return nil
---@deprecated Removed on 2026-08-22 — use oxmysql directly.
function SQL.Create(tableName, columns)
warnDeprecated()
assert(MySQL, "Tried using module SQL without MySQL being loaded")
local columnsList = {}
for i, column in pairs(columns) do
assert(type(column.type) == "string", "SQL: column type must be a string")
table.insert(columnsList, string.format("%s %s", quoteIdentifier(column.name), column.type))
end
local query = string.format("CREATE TABLE IF NOT EXISTS %s (%s);",
quoteIdentifier(tableName),
table.concat(columnsList, ", ")
)
MySQL.query.await(query)
end
-- insert if not exist otherwise update
---@deprecated Removed on 2026-08-22 — use oxmysql directly.
function SQL.InsertOrUpdate(tableName, data)
warnDeprecated()
assert(MySQL, "Tried using module SQL without MySQL being loaded")
local columns = {}
local placeholders = {}
local updates = {}
local params = {}
for column, value in pairs(data) do
local quoted = quoteIdentifier(column)
table.insert(columns, quoted)
table.insert(placeholders, "?")
table.insert(updates, quoted .. " = VALUES(" .. quoted .. ")") -- Use VALUES() for update
table.insert(params, value)
end
local query = string.format(
"INSERT INTO %s (%s) VALUES (%s) ON DUPLICATE KEY UPDATE %s;",
quoteIdentifier(tableName),
table.concat(columns, ", "),
table.concat(placeholders, ", "),
table.concat(updates, ", ")
)
MySQL.query.await(query, params)
end
--- Selects rows matching the given filters.
-- @param tableName The table to query.
-- @param where Table of column = value pairs, joined with AND. Example: { citizenid = cid }
---@deprecated Removed on 2026-08-22 — use oxmysql directly.
function SQL.Get(tableName, where)
warnDeprecated()
assert(MySQL, "Tried using module SQL without MySQL being loaded")
local conditions, params = buildWhere(where)
local query = string.format("SELECT * FROM %s WHERE %s;", quoteIdentifier(tableName), conditions)
local result = MySQL.query.await(query, params)
return result
end
---@deprecated Removed on 2026-08-22 — use oxmysql directly.
function SQL.GetAll(tableName)
warnDeprecated()
assert(MySQL, "Tried using module SQL without MySQL being loaded")
local query = string.format("SELECT * FROM %s;", quoteIdentifier(tableName))
local result = MySQL.query.await(query)
return result
end
--- Deletes rows matching the given filters.
-- @param tableName The table to delete from.
-- @param where Table of column = value pairs, joined with AND. Example: { citizenid = cid }
---@deprecated Removed on 2026-08-22 — use oxmysql directly.
function SQL.Delete(tableName, where)
warnDeprecated()
assert(MySQL, "Tried using module SQL without MySQL being loaded")
local conditions, params = buildWhere(where)
local query = string.format("DELETE FROM %s WHERE %s;", quoteIdentifier(tableName), conditions)
MySQL.query.await(query, params)
end
exports('SQL', function()
warnDeprecated()
return SQL
end)
return SQL
-72
View File
@@ -1,72 +0,0 @@
Ids = Ids or {}
---This will generate a unique id.
---@param tbl table | nil
---@param len number | nil
---@param pattern string | nil
---@return string
Ids.CreateUniqueId = function(tbl, len, pattern) -- both optional
tbl = tbl or {} -- table to check uniqueness. Ids to check against must be the key to the tables value
len = len or 8
local id = ""
for i = 1, len do
local char = ""
if pattern then
local charIndex = math.random(1, #pattern)
char = pattern:sub(charIndex, charIndex)
else
char = math.random(1, 2) == 1 and string.char(math.random(65, 90)) or string.format("%d", math.random(10) - 1) -- CAP letter and number
end
id = id .. char
end
if tbl[id] then
return Ids.CreateUniqueId(tbl, len, pattern)
end
return id
end
---This will generate a unique id.
---@param tbl table
---@param len number
---@return string
Ids.RandomUpper = function(tbl, len)
return Ids.CreateUniqueId(tbl, len, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
end
---This will generate a unique id.
---@param tbl table
---@param len number
---@return string
Ids.RandomLower = function(tbl, len)
return Ids.CreateUniqueId(tbl, len, "abcdefghijklmnopqrstuvwxyz")
end
---This will generate a unique id.
---@param tbl table
---@param len number
---@return string
Ids.RandomString = function(tbl, len)
return Ids.CreateUniqueId(tbl, len, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
end
---This will generate a unique id.
---@param tbl table
---@param len number
---@return string
Ids.RandomNumber = function(tbl, len)
return Ids.CreateUniqueId(tbl, len, "0123456789")
end
---This will generate a unique id.
---@param tbl table
---@param len number
---@return string
Ids.Random = function(tbl, len)
return Ids.CreateUniqueId(tbl, len)
end
exports("Ids", Ids)
return Ids
-207
View File
@@ -1,207 +0,0 @@
Math = Math or {}
---@class Math
---@field public name string @add name field to class Car, you'll see it in code completion
Math = {}
--- Rounds a number to the nearest whole number.
---@param value number: The value to round.
---@return number: The rounded value.
function Math.Round(value)
return math.floor(value + 0.5)
end
function Math.Truncate(value, decimals)
local mul = decimals and (10 ^ decimals) or 1
if value < 0 then
return math.ceil(value * mul) / mul
else
return math.floor(value * mul) / mul
end
end
--- Warps the number around from max to min and vice versa.
---@param value number: The value to wrap.
---@param min number: The minimum value.
---@param max number: The maximum value.
---@return number: The wrapped value.
function Math.Wrap(value, min, max)
local range = max - min
return (value - min) % range + min
end
--- Gets an interpolated value between two numbers.
---@see https://en.wikipedia.org/wiki/Smoothstep
---@param value number The interpolation value.
---@param min number : The minimum value.
---@param max number : The maximum value.
---@return number The interpolated value.
function Math.Smooth(value, min, max)
value = Math.Clamp((value - min) / (max - min), 0, 1)
return value * value * (3 - 2 * value)
end
--- Gets the nearest whole number.
--- @param value number The value to round.
--- @return number The rounded value.
function Math.Nearest(value)
return math.floor(value + 0.5)
end
--- Maps a value from one range to another.
---@param value number The value to map.
---@param inMin number The minimum value for the provided value.
---@param inMax number The maximum value for the provided value.
---@param outMin number The minimum value for the output.
---@param outMax number The maximum value for the output.
function Math.Map(value, inMin, inMax, outMin, outMax)
return (value - inMin) / (inMax - inMin) * (outMax - outMin) + outMin
end
function Math.Clamp(value, min, max)
return math.min(math.max(value, min), max)
end
function Math.Remap(value, min, max, newMin, newMax)
return newMin + (value - min) / (max - min) * (newMax - newMin)
end
function Math.PointInRadius(radius)
local angle = math.rad(math.random(0, 360))
return vector2(radius * math.cos(angle), radius * math.sin(angle))
end
function Math.Normalize(value, min, max)
if max == min then return 0 end -- Avoid division by zero
return (value - min) / (max - min)
end
function Math.Normalize2D(x, y)
if type(x) == "vector2" then
x, y = x.x, x.y
end
local length = math.sqrt(x*x + y*y)
return length ~= 0 and vector2(x / length, y / length) or vector2(0, 0)
end
function Math.Normalize3D(x, y, z)
if type(x) == "vector3" then
x, y, z = x.x, x.y, x.z
end
local length = math.sqrt(x*x + y*y + z*z)
return length ~= 0 and vector3(x / length, y / length, z / length) or vector3(0, 0, 0)
end
function Math.Normalize4D(x, y, z, w)
if type(x) == "vector4" then
x, y, z, w = x.x, x.y, x.z, x.w
end
local length = math.sqrt(x*x + y*y + z*z + w*w)
return length ~= 0 and vector4(x / length, y / length, z / length, w / length) or vector4(0, 0, 0, 0)
end
function Math.DirectionToTarget(fromV3, toV3)
return Math.Normalize3D(toV3.x - fromV3.x, toV3.y - fromV3.y, toV3.z - fromV3.z)
end
function Deg2Rad(deg)
return deg * math.pi / 180.0
end
function RotVector(pos, rot)
local pitch = Deg2Rad(rot.x)
local roll = Deg2Rad(rot.y)
local yaw = Deg2Rad(rot.z)
local cosY = math.cos(yaw)
local sinY = math.sin(yaw)
local cosP = math.cos(pitch)
local sinP = math.sin(pitch)
local cosR = math.cos(roll)
local sinR = math.sin(roll)
local m11 = cosY * cosR + sinY * sinP * sinR
local m12 = sinR * cosP
local m13 = -sinY * cosR + cosY * sinP * sinR
local m21 = -cosY * sinR + sinY * sinP * cosR
local m22 = cosR * cosP
local m23 = sinR * sinY + cosY * sinP * cosR
local m31 = sinY * cosP
local m32 = -sinP
local m33 = cosY * cosP
return vector3(pos.x * m11 + pos.y * m21 + pos.z * m31, pos.x * m12 + pos.y * m22 + pos.z * m32, pos.x * m13 + pos.y * m23 + pos.z * m33)
end
function Math.GetOffsetFromMatrix(position, rotation, offset)
local rotated = RotVector(offset, rotation)
print("Rotated: " .. tostring(rotated))
return position + rotated
end
function Math.InBoundary(pos, boundary)
if not boundary then return true end
local x, y, z = table.unpack(pos)
-- Handle legacy min/max boundary format for backwards compatibility
if boundary.min and boundary.max then
local minX, minY, minZ = table.unpack(boundary.min)
local maxX, maxY, maxZ = table.unpack(boundary.max)
return x >= minX and x <= maxX and y >= minY and y <= maxY and z >= minZ and z <= maxZ
end
-- Handle list of points (polygon boundary)
if boundary.points and #boundary.points > 0 then
local points = boundary.points
local minZ = boundary.minZ or -math.huge
local maxZ = boundary.maxZ or math.huge
-- Check Z bounds first
if z < minZ or z > maxZ then
return false
end
-- Point-in-polygon test using ray casting algorithm (improved version)
local inside = false
local n = #points
for i = 1, n do
local j = i == n and 1 or i + 1 -- Next point (wrap around)
local xi, yi = points[i].x or points[i][1], points[i].y or points[i][2]
local xj, yj = points[j].x or points[j][1], points[j].y or points[j][2]
-- Ensure xi, yi, xj, yj are numbers
if not (xi and yi and xj and yj) then
goto continue
end
-- Ray casting test
if ((yi > y) ~= (yj > y)) then
-- Calculate intersection point
local intersect = (xj - xi) * (y - yi) / (yj - yi) + xi
if x < intersect then
inside = not inside
end
end
::continue::
end
return inside
end
-- Fallback to true if boundary format is not recognized
return true
end
exports('Math', Math)
return Math
-65
View File
@@ -1,65 +0,0 @@
Prints = Prints or {}
local function handle(result, value)
if type(value) == 'function' then
return tostring(value)
end
return result
end
local function format(color, ...)
local data = {...}
for i = 1, #data do
if data[i] == nil then
data[i] = 'nil'
end
end
local newForm = {}
local jsonDecode = {sort_keys = true, indent = true, exception = handle}
for k, v in pairs(data) do
local formatted
if type(v) == 'table' then
formatted = json.encode(v, jsonDecode)
elseif type(v) == 'number' then
formatted = tostring(v)
elseif type(v) == 'boolean' then
formatted = tostring(v)
elseif type(v) == 'nil' then
formatted = 'nil Value'
elseif type(v) == 'string' then
formatted = v
elseif type(v) == 'function' then
formatted = tostring(v)
else
formatted = tostring(v)
end
table.insert(newForm, color .. formatted)
end
return table.concat(newForm, color .. ' \n ')
end
---This will print a colored message to the console with the designated prefix.
---@param message string
Prints.Info = function(...)
print('^5 [INFO] '.. format('^5 ', ...))
end
---This will print a colored message to the console with the designated prefix.
---@param message string
Prints.Warn = function(...)
print('^3 [WARN] '.. format('^3', ...))
end
---This will print a colored message to the console with the designated prefix.
---@param message string
Prints.Error = function(...)
print('^1 [ERROR] '.. format('^1', ...))
end
---This will print a colored message to the console with the designated prefix.
---@param message string
Prints.Debug = function(...)
print('^2 [DEBUG] '.. format('^2', ...))
end
return Prints
-138
View File
@@ -1,138 +0,0 @@
Table = {}
Table.CheckPopulated = function(tbl)
if #tbl == 0 then
for _, _ in pairs(tbl) do
return true
end
return false
end
return true
end
Table.DeepClone = function(tbl, out, omit)
if type(tbl) ~= "table" then return tbl end
local new = out or {}
omit = omit or {}
for key, data in pairs(tbl) do
if not omit[key] then
if type(data) == "table" then
new[key] = Table.DeepClone(data)
else
new[key] = data
end
end
end
return new
end
Table.TableContains = function(tbl, search, nested)
for _, v in pairs(tbl) do
if nested and type(v) == "table" then
return Table.TableContains(v, search)
elseif v == search then
return true, v
end
end
return false
end
Table.TableContainsKey = function(tbl, search)
for k, _ in pairs(tbl) do
if k == search then
return true, k
end
end
return false
end
Table.TableGetKeys = function(tbl)
local keys = {}
for k ,_ in pairs(tbl) do
table.insert(keys,k)
end
return keys
end
Table.GetClosest = function(coords, tbl)
local closestPoint = nil
local dist = math.huge
for k, v in pairs(tbl) do
local c = v.coords
local d = c and #(coords - c)
if d < dist then
dist = d
closestPoint = v
end
end
return closestPoint
end
Table.FindFirstUnoccupiedSlot = function(tbl)
local occupiedSlots = {}
for _, v in pairs(tbl) do
if v.slot then
occupiedSlots[v.slot] = true
end
end
for i = 1, BridgeServerConfig.MaxInventorySlots do
if not occupiedSlots[i] then
return i
end
end
return nil
end
Table.Append = function(tbl1, tbl2)
for _, v in pairs(tbl2) do
table.insert(tbl1, v)
end
return tbl1
end
Table.Split = function(tbl, size)
local new1 = {}
local new2 = {}
size = size or math.floor(#tbl / 2)
if size > #tbl then
assert(false, "Size is greater than the length of the table.")
end
for i = 1, size do
table.insert(new1, tbl[i])
end
for i = size + 1, #tbl do
table.insert(new2, tbl[i])
end
return new1, new2
end
Table.Shuffle = function(tbl)
for i = #tbl, 2, -1 do
local j = math.random(i)
tbl[i], tbl[j] = tbl[j], tbl[i]
end
return tbl
end
Table.Compare = function(a, b)
if type(a) == "table" then
for k, v in pairs(a) do
if not Table.Compare(v, b[k]) then return false end
end
return true
else
return a == b
end
end
Table.Count = function(tbl)
local count = 0
for _ in pairs(tbl) do
count = count + 1
end
return count
end
exports("Table", Table)
return Table
-510
View File
@@ -1,510 +0,0 @@
---@diagnostic disable: duplicate-set-field
Vehicles = Vehicles or {}
-- Vehicle properties setter function
--
-- Inspired by and derived from vehicle property handlers in:
-- ESX Framework (https://github.com/esx-framework/esx_core) [License: GPLv3]
-- QBCore Framework (https://github.com/qbcore-framework/qb-core) [License: GPLv3]
--
-- Note: The ox_lib version (https://github.com/overextended/ox_lib) [License: LGPLv3] also draws heavily from these projects.
--
-- This code is licensed under the GNU General Public License v3.0 (GPLv3).
-- You may use, modify, and distribute this code under the terms of the GPLv3.
-- See LICENSE file for full details.
if not DecorIsRegisteredAsType("Player_Vehicle", 3) then DecorRegister("Player_Vehicle", 3) end
---@alias RGBColor number[] RGB color array [r, g, b] where each component is 0-255
---@alias VehicleExtras table<number, number> Vehicle extras where key is extra ID and value is state (0=enabled, 1=disabled)
---@class VehicleProperties
---@field model? number Vehicle model hash
---@field plate? string License plate text
---@field plateIndex? number License plate style index (0-5)
---@field bodyHealth? number Body health (0-1000)
---@field engineHealth? number Engine health (0-1000)
---@field tankHealth? number Tank health (0-1000)
---@field fuelLevel? number Fuel level (0-100)
---@field oilLevel? number Oil level (0-100)
---@field dirtLevel? number Dirt level (0-15)
---@field paintType1? number Primary paint type
---@field paintType2? number Secondary paint type
---@field color1? number|RGBColor Primary color (color index or RGB values)
---@field color2? number|RGBColor Secondary color (color index or RGB values)
---@field pearlescentColor? number Pearlescent color index
---@field interiorColor? number Interior color index
---@field dashboardColor? number Dashboard color index
---@field wheelColor? number Wheel color index
---@field wheelWidth? number Wheel width
---@field wheelSize? number Wheel size
---@field wheels? number Wheel type
---@field windowTint? number Window tint level (0-6)
---@field xenonColor? number Xenon headlight color
---@field neonEnabled? boolean[] Neon light states [left, right, front, back]
---@field neonColor? RGBColor Neon light color RGB values
---@field extras? VehicleExtras Vehicle extras configuration
---@field tyreSmokeColor? RGBColor Tyre smoke color RGB values
---@field modSpoilers? number Spoiler modification (-1 to max)
---@field modFrontBumper? number Front bumper modification (-1 to max)
---@field modRearBumper? number Rear bumper modification (-1 to max)
---@field modSideSkirt? number Side skirt modification (-1 to max)
---@field modExhaust? number Exhaust modification (-1 to max)
---@field modFrame? number Frame modification (-1 to max)
---@field modGrille? number Grille modification (-1 to max)
---@field modHood? number Hood modification (-1 to max)
---@field modFender? number Fender modification (-1 to max)
---@field modRightFender? number Right fender modification (-1 to max)
---@field modRoof? number Roof modification (-1 to max)
---@field modEngine? number Engine modification (-1 to max)
---@field modBrakes? number Brakes modification (-1 to max)
---@field modTransmission? number Transmission modification (-1 to max)
---@field modSuspension? number Suspension modification (-1 to max)
---@field modArmor? number Armor modification (-1 to max)
---@field modNitrous? number Nitrous modification (-1 to max)
---@field modHorns? number Horn modification (-1 to max)
---@field modSubwoofer? number Subwoofer modification (-1 to max)
---@field modTurbo? boolean Turbo toggle
---@field modSmokeEnabled? boolean Tyre smoke toggle
---@field modHydraulics? boolean Hydraulics toggle
---@field modXenon? boolean Xenon lights toggle
---@field modFrontWheels? number Front wheels modification (-1 to max)
---@field modBackWheels? number Back wheels modification (-1 to max)
---@field modCustomTiresF? boolean Custom front tires enabled
---@field modCustomTiresR? boolean Custom rear tires enabled
---@field modPlateHolder? number Plate holder modification (-1 to max)
---@field modVanityPlate? number Vanity plate modification (-1 to max)
---@field modTrimA? number Trim A modification (-1 to max)
---@field modOrnaments? number Ornaments modification (-1 to max)
---@field modDashboard? number Dashboard modification (-1 to max)
---@field modDial? number Dial modification (-1 to max)
---@field modDoorSpeaker? number Door speaker modification (-1 to max)
---@field modSeats? number Seats modification (-1 to max)
---@field modSteeringWheel? number Steering wheel modification (-1 to max)
---@field modShifterLeavers? number Shifter levers modification (-1 to max)
---@field modAPlate? number A-plate modification (-1 to max)
---@field modSpeakers? number Speakers modification (-1 to max)
---@field modTrunk? number Trunk modification (-1 to max)
---@field modHydrolic? number Hydraulic modification (-1 to max)
---@field modEngineBlock? number Engine block modification (-1 to max)
---@field modAirFilter? number Air filter modification (-1 to max)
---@field modStruts? number Struts modification (-1 to max)
---@field modArchCover? number Arch cover modification (-1 to max)
---@field modAerials? number Aerials modification (-1 to max)
---@field modTrimB? number Trim B modification (-1 to max)
---@field modTank? number Tank modification (-1 to max)
---@field modWindows? number Windows modification (-1 to max)
---@field modDoorR? number Door R modification (-1 to max)
---@field modLivery? number Livery modification (-1 to max)
---@field modLightbar? number Lightbar modification (-1 to max)
---@field modRoofLivery? number Roof livery modification (-1 to max)
---@field livery? number Vehicle livery (-1 to max)
---@field windows? number[] Array of damaged window indices
---@field doors? number[] Array of damaged door indices
---@field tyres? table<number, number> Map of tyre index to damage state (1=burst, 2=destroyed)
---@field bulletProofTyres? boolean Bulletproof tyres enabled
---@field driftTyres? boolean Drift tyres enabled
---@field doorLockStatus? number Door lock status (0=none, 1=unlocked, 2=locked, 3=lockout, 4=can't enter)
---@field brokenWheels? number|number[] Single wheel index or array of wheel indices to break off (0-7)
-- Handle state bag changes for vehicle properties
AddStateBagChangeHandler('community_bridge:SetVehicleProperties', '', function(bagName, _, value)
if not value or not GetEntityFromStateBagName then return end
-- Wait for entity to exist with timeout
local entity = nil
local attempts = 0
local maxAttempts = 100 -- 10 seconds at 100ms intervals
while not entity and attempts < maxAttempts do
local tempEntity = GetEntityFromStateBagName(bagName)
if tempEntity and tempEntity > 0 and DoesEntityExist(tempEntity) then
entity = tempEntity
break
end
attempts = attempts + 1
Wait(100)
end
if not entity then return end
-- Apply vehicle properties from state bag (prevents infinite loops)
Vehicles.SetVehicleProperties(entity, value, true)
Wait(500)
-- Clear state if we own the entity (prevents accumulation)
if NetworkGetEntityOwner(entity) == PlayerId() then
Vehicles.SetVehicleProperties(entity, value, true)
Entity(entity).state:set('community_bridge:SetVehicleProperties', nil, false)
end
end)
local gameBuild = GetGameBuildNumber()
---Get comprehensive vehicle properties
---@param vehicle number The vehicle entity handle
---@return VehicleProperties|nil properties Table containing all vehicle properties, or nil if vehicle doesn't exist
function Vehicles.GetVehicleProperties(vehicle)
if not DoesEntityExist(vehicle) then return end
local colorPrimary, colorSecondary = GetVehicleColours(vehicle)
local pearlescentColor, wheelColor = GetVehicleExtraColours(vehicle)
local paintType1 = GetVehicleModColor_1(vehicle)
local paintType2 = GetVehicleModColor_2(vehicle)
-- Handle custom colors (can be either number or table)
local primaryColor = colorPrimary --[[@as number|table]]
local secondaryColor = colorSecondary --[[@as number|table]]
if GetIsVehiclePrimaryColourCustom(vehicle) then
local r, g, b = GetVehicleCustomPrimaryColour(vehicle)
primaryColor = { r, g, b }
end
if GetIsVehicleSecondaryColourCustom(vehicle) then
local r, g, b = GetVehicleCustomSecondaryColour(vehicle)
secondaryColor = { r, g, b }
end
-- Get vehicle extras
local extras = {}
for i = 1, 15 do
if DoesExtraExist(vehicle, i) then
extras[i] = IsVehicleExtraTurnedOn(vehicle, i) and 0 or 1
end
end
-- Get vehicle damage information
local damage = {
windows = {},
doors = {},
tyres = {},
brokenWheels = {},
}
-- Check window damage
local windows = 0
for i = 0, 7 do
RollUpWindow(vehicle, i)
if not IsVehicleWindowIntact(vehicle, i) then
windows += 1
damage.windows[windows] = i
end
end
-- Check door damage
local doors = 0
for i = 0, 5 do
if IsVehicleDoorDamaged(vehicle, i) then
doors += 1
damage.doors[doors] = i
end
end
-- Check tyre damage
for i = 0, 7 do
if IsVehicleTyreBurst(vehicle, i, false) then
damage.tyres[i] = IsVehicleTyreBurst(vehicle, i, true) and 2 or 1
end
end
-- Check broken wheels
for i = 0, 7 do
if IsVehicleWheelBrokenOff(vehicle, i) then
table.insert(damage.brokenWheels, i)
end
end
-- Get neon light status
local neons = {}
for i = 0, 3 do
neons[i + 1] = IsVehicleNeonLightEnabled(vehicle, i)
end
return {
model = GetEntityModel(vehicle),
plate = GetVehicleNumberPlateText(vehicle),
plateIndex = GetVehicleNumberPlateTextIndex(vehicle),
bodyHealth = math.floor(GetVehicleBodyHealth(vehicle) + 0.5),
engineHealth = math.floor(GetVehicleEngineHealth(vehicle) + 0.5),
tankHealth = math.floor(GetVehiclePetrolTankHealth(vehicle) + 0.5),
fuelLevel = math.floor(GetVehicleFuelLevel(vehicle) + 0.5),
oilLevel = math.floor(GetVehicleOilLevel(vehicle) + 0.5),
dirtLevel = math.floor(GetVehicleDirtLevel(vehicle) + 0.5),
paintType1 = paintType1,
paintType2 = paintType2,
color1 = primaryColor,
color2 = secondaryColor,
pearlescentColor = pearlescentColor,
interiorColor = GetVehicleInteriorColor(vehicle),
dashboardColor = GetVehicleDashboardColour(vehicle),
wheelColor = wheelColor,
wheelWidth = GetVehicleWheelWidth(vehicle),
wheelSize = GetVehicleWheelSize(vehicle),
wheels = GetVehicleWheelType(vehicle),
windowTint = GetVehicleWindowTint(vehicle),
xenonColor = GetVehicleXenonLightsColor(vehicle),
neonEnabled = neons,
neonColor = { GetVehicleNeonLightsColour(vehicle) },
extras = extras,
tyreSmokeColor = { GetVehicleTyreSmokeColor(vehicle) },
modSpoilers = GetVehicleMod(vehicle, 0),
modFrontBumper = GetVehicleMod(vehicle, 1),
modRearBumper = GetVehicleMod(vehicle, 2),
modSideSkirt = GetVehicleMod(vehicle, 3),
modExhaust = GetVehicleMod(vehicle, 4),
modFrame = GetVehicleMod(vehicle, 5),
modGrille = GetVehicleMod(vehicle, 6),
modHood = GetVehicleMod(vehicle, 7),
modFender = GetVehicleMod(vehicle, 8),
modRightFender = GetVehicleMod(vehicle, 9),
modRoof = GetVehicleMod(vehicle, 10),
modEngine = GetVehicleMod(vehicle, 11),
modBrakes = GetVehicleMod(vehicle, 12),
modTransmission = GetVehicleMod(vehicle, 13),
modHorns = GetVehicleMod(vehicle, 14),
modSuspension = GetVehicleMod(vehicle, 15),
modArmor = GetVehicleMod(vehicle, 16),
modNitrous = GetVehicleMod(vehicle, 17),
modTurbo = IsToggleModOn(vehicle, 18),
modSubwoofer = GetVehicleMod(vehicle, 19),
modSmokeEnabled = IsToggleModOn(vehicle, 20),
modHydraulics = IsToggleModOn(vehicle, 21),
modXenon = IsToggleModOn(vehicle, 22),
modFrontWheels = GetVehicleMod(vehicle, 23),
modBackWheels = GetVehicleMod(vehicle, 24),
modCustomTiresF = GetVehicleModVariation(vehicle, 23),
modCustomTiresR = GetVehicleModVariation(vehicle, 24),
modPlateHolder = GetVehicleMod(vehicle, 25),
modVanityPlate = GetVehicleMod(vehicle, 26),
modTrimA = GetVehicleMod(vehicle, 27),
modOrnaments = GetVehicleMod(vehicle, 28),
modDashboard = GetVehicleMod(vehicle, 29),
modDial = GetVehicleMod(vehicle, 30),
modDoorSpeaker = GetVehicleMod(vehicle, 31),
modSeats = GetVehicleMod(vehicle, 32),
modSteeringWheel = GetVehicleMod(vehicle, 33),
modShifterLeavers = GetVehicleMod(vehicle, 34),
modAPlate = GetVehicleMod(vehicle, 35),
modSpeakers = GetVehicleMod(vehicle, 36),
modTrunk = GetVehicleMod(vehicle, 37),
modHydrolic = GetVehicleMod(vehicle, 38),
modEngineBlock = GetVehicleMod(vehicle, 39),
modAirFilter = GetVehicleMod(vehicle, 40),
modStruts = GetVehicleMod(vehicle, 41),
modArchCover = GetVehicleMod(vehicle, 42),
modAerials = GetVehicleMod(vehicle, 43),
modTrimB = GetVehicleMod(vehicle, 44),
modTank = GetVehicleMod(vehicle, 45),
modWindows = GetVehicleMod(vehicle, 46),
modDoorR = GetVehicleMod(vehicle, 47),
modLivery = GetVehicleMod(vehicle, 48),
modRoofLivery = GetVehicleRoofLivery(vehicle),
modLightbar = GetVehicleMod(vehicle, 49),
livery = GetVehicleLivery(vehicle),
windows = damage.windows,
doors = damage.doors,
tyres = damage.tyres,
brokenWheels = damage.brokenWheels,
bulletProofTyres = GetVehicleTyresCanBurst(vehicle),
driftTyres = gameBuild >= 2372 and GetDriftTyresEnabled(vehicle),
doorLockStatus = GetVehicleDoorLockStatus(vehicle),
}
end
---Apply vehicle properties to a vehicle
---@param vehicle number The vehicle entity handle
---@param props VehicleProperties Table containing vehicle properties to apply
---@param fromStateBag? boolean Internal flag to prevent infinite loops when called from state bag handler
function Vehicles.SetVehicleProperties(vehicle, props, fromStateBag)
if not DoesEntityExist(vehicle) then return false end
local colorPrimary, colorSecondary = GetVehicleColours(vehicle)
local pearlescentColor, wheelColor = GetVehicleExtraColours(vehicle)
SetVehicleModKit(vehicle, 0)
-- Apply vehicle extras
if props.extras then
for id, disable in pairs(props.extras) do
local extraId = tonumber(id)
if extraId then
SetVehicleExtra(vehicle, extraId, disable == 1)
end
end
end
if props.plate then SetVehicleNumberPlateText(vehicle, props.plate) end
if props.plateIndex then SetVehicleNumberPlateTextIndex(vehicle, props.plateIndex) end
if props.bodyHealth then SetVehicleBodyHealth(vehicle, props.bodyHealth + 0.0) end
if props.engineHealth then SetVehicleEngineHealth(vehicle, props.engineHealth + 0.0) end
if props.tankHealth then SetVehiclePetrolTankHealth(vehicle, props.tankHealth + 0.0) end
if props.fuelLevel then SetVehicleFuelLevel(vehicle, props.fuelLevel + 0.0) end
if props.oilLevel then SetVehicleOilLevel(vehicle, props.oilLevel + 0.0) end
if props.dirtLevel then SetVehicleDirtLevel(vehicle, props.dirtLevel + 0.0) end
-- Apply vehicle colors
if props.color1 then
if type(props.color1) == 'number' then
ClearVehicleCustomPrimaryColour(vehicle)
SetVehicleColours(vehicle, props.color1 --[[@as number]], colorSecondary --[[@as number]])
else
if props.paintType1 then
SetVehicleModColor_1(vehicle, props.paintType1, 0, props.pearlescentColor or 0)
end
SetVehicleCustomPrimaryColour(vehicle, props.color1[1], props.color1[2], props.color1[3])
end
end
if props.color2 then
if type(props.color2) == 'number' then
ClearVehicleCustomSecondaryColour(vehicle)
SetVehicleColours(vehicle, props.color1 or colorPrimary --[[@as number]], props.color2 --[[@as number]])
else
if props.paintType2 then
SetVehicleModColor_2(vehicle, props.paintType2, 0)
end
SetVehicleCustomSecondaryColour(vehicle, props.color2[1], props.color2[2], props.color2[3])
end
end
if props.pearlescentColor or props.wheelColor then
SetVehicleExtraColours(vehicle, props.pearlescentColor or pearlescentColor, props.wheelColor or wheelColor)
end
if props.interiorColor then SetVehicleInteriorColor(vehicle, props.interiorColor) end
if props.dashboardColor then SetVehicleDashboardColor(vehicle, props.dashboardColor) end
-- Apply wheel properties
if props.wheels then SetVehicleWheelType(vehicle, props.wheels) end
if props.wheelSize then SetVehicleWheelSize(vehicle, props.wheelSize) end
if props.wheelWidth then
SetVehicleWheelWidth(vehicle, props.wheelWidth)
end
-- Apply window and lighting properties
if props.windowTint then SetVehicleWindowTint(vehicle, props.windowTint) end
if props.neonEnabled then
for i = 1, #props.neonEnabled do
SetVehicleNeonLightEnabled(vehicle, i - 1, props.neonEnabled[i])
end
end
if props.neonColor then SetVehicleNeonLightsColour(vehicle, props.neonColor[1], props.neonColor[2], props.neonColor[3]) end
-- Apply vehicle damage
if props.windows then
for i = 1, #props.windows do
RemoveVehicleWindow(vehicle, props.windows[i])
end
end
if props.doors then
for i = 1, #props.doors do
SetVehicleDoorBroken(vehicle, props.doors[i], true)
end
end
if props.tyres then
for tyre, state in pairs(props.tyres) do
SetVehicleTyreBurst(vehicle, tonumber(tyre) --[[@as number]], state == 2, 1000.0)
end
end
if props.brokenWheels then
if type(props.brokenWheels) == 'number' then
BreakOffVehicleWheel(vehicle, props.brokenWheels --[[@as number]], false, true, true, false)
else
for i = 1, #props.brokenWheels do
BreakOffVehicleWheel(vehicle, props.brokenWheels[i], false, true, true, false)
end
end
end
if props.modSmokeEnabled ~= nil then ToggleVehicleMod(vehicle, 20, props.modSmokeEnabled) end
if props.tyreSmokeColor then SetVehicleTyreSmokeColor(vehicle, props.tyreSmokeColor[1], props.tyreSmokeColor[2], props.tyreSmokeColor[3]) end
if props.modSpoilers then SetVehicleMod(vehicle, 0, props.modSpoilers, false) end
if props.modFrontBumper then SetVehicleMod(vehicle, 1, props.modFrontBumper, false) end
if props.modRearBumper then SetVehicleMod(vehicle, 2, props.modRearBumper, false) end
if props.modSideSkirt then SetVehicleMod(vehicle, 3, props.modSideSkirt, false) end
if props.modExhaust then SetVehicleMod(vehicle, 4, props.modExhaust, false) end
if props.modFrame then SetVehicleMod(vehicle, 5, props.modFrame, false) end
if props.modGrille then SetVehicleMod(vehicle, 6, props.modGrille, false) end
if props.modHood then SetVehicleMod(vehicle, 7, props.modHood, false) end
if props.modFender then SetVehicleMod(vehicle, 8, props.modFender, false) end
if props.modRightFender then SetVehicleMod(vehicle, 9, props.modRightFender, false) end
if props.modRoof then SetVehicleMod(vehicle, 10, props.modRoof, false) end
if props.modEngine then SetVehicleMod(vehicle, 11, props.modEngine, false) end
if props.modBrakes then SetVehicleMod(vehicle, 12, props.modBrakes, false) end
if props.modTransmission then SetVehicleMod(vehicle, 13, props.modTransmission, false) end
if props.modSuspension then SetVehicleMod(vehicle, 15, props.modSuspension, false) end
if props.modArmor then SetVehicleMod(vehicle, 16, props.modArmor, false) end
if props.modNitrous then SetVehicleMod(vehicle, 17, props.modNitrous, false) end
if props.modTurbo ~= nil then ToggleVehicleMod(vehicle, 18, props.modTurbo) end
if props.modSubwoofer ~= nil then ToggleVehicleMod(vehicle, 19, props.modSubwoofer) end
if props.modHydraulics ~= nil then ToggleVehicleMod(vehicle, 21, props.modHydraulics) end
if props.modXenon ~= nil then ToggleVehicleMod(vehicle, 22, props.modXenon) end
if props.modHorns then SetVehicleMod(vehicle, 14, props.modHorns, false) end
if props.xenonColor then SetVehicleXenonLightsColor(vehicle, props.xenonColor) end
if props.modFrontWheels then SetVehicleMod(vehicle, 23, props.modFrontWheels, props.modCustomTiresF) end
if props.modBackWheels then SetVehicleMod(vehicle, 24, props.modBackWheels, props.modCustomTiresR) end
if props.modPlateHolder then SetVehicleMod(vehicle, 25, props.modPlateHolder, false) end
if props.modVanityPlate then SetVehicleMod(vehicle, 26, props.modVanityPlate, false) end
if props.modTrimA then SetVehicleMod(vehicle, 27, props.modTrimA, false) end
if props.modOrnaments then SetVehicleMod(vehicle, 28, props.modOrnaments, false) end
if props.modDashboard then SetVehicleMod(vehicle, 29, props.modDashboard, false) end
if props.modDial then SetVehicleMod(vehicle, 30, props.modDial, false) end
if props.modDoorSpeaker then SetVehicleMod(vehicle, 31, props.modDoorSpeaker, false) end
if props.modSeats then SetVehicleMod(vehicle, 32, props.modSeats, false) end
if props.modSteeringWheel then SetVehicleMod(vehicle, 33, props.modSteeringWheel, false) end
if props.modShifterLeavers then SetVehicleMod(vehicle, 34, props.modShifterLeavers, false) end
if props.modAPlate then SetVehicleMod(vehicle, 35, props.modAPlate, false) end
if props.modSpeakers then SetVehicleMod(vehicle, 36, props.modSpeakers, false) end
if props.modTrunk then SetVehicleMod(vehicle, 37, props.modTrunk, false) end
if props.modHydrolic then SetVehicleMod(vehicle, 38, props.modHydrolic, false) end
if props.modEngineBlock then SetVehicleMod(vehicle, 39, props.modEngineBlock, false) end
if props.modAirFilter then SetVehicleMod(vehicle, 40, props.modAirFilter, false) end
if props.modStruts then SetVehicleMod(vehicle, 41, props.modStruts, false) end
if props.modArchCover then SetVehicleMod(vehicle, 42, props.modArchCover, false) end
if props.modAerials then SetVehicleMod(vehicle, 43, props.modAerials, false) end
if props.modTrimB then SetVehicleMod(vehicle, 44, props.modTrimB, false) end
if props.modTank then SetVehicleMod(vehicle, 45, props.modTank, false) end
if props.modWindows then SetVehicleMod(vehicle, 46, props.modWindows, false) end
if props.modDoorR then SetVehicleMod(vehicle, 47, props.modDoorR, false) end
if props.modLivery then SetVehicleMod(vehicle, 48, props.modLivery, false) end
if props.modLightbar then SetVehicleMod(vehicle, 49, props.modLightbar, false) end
if props.modRoofLivery then SetVehicleRoofLivery(vehicle, props.modRoofLivery) end
if props.livery then SetVehicleLivery(vehicle, props.livery) end
if props.bulletProofTyres ~= nil then SetVehicleTyresCanBurst(vehicle, props.bulletProofTyres) end
if gameBuild >= 2372 and props.driftTyres then SetDriftTyresEnabled(vehicle, true) end
if props.doorLockStatus then
SetVehicleDoorsLocked(vehicle, props.doorLockStatus)
end
if not DecorExistOn(vehicle, "Player_Vehicle") then DecorSetInt(vehicle, "Player_Vehicle", -1) end
-- Only sync to other clients if not called from state bag AND we own the entity
if not fromStateBag and NetworkGetEntityIsNetworked(vehicle) and NetworkGetEntityOwner(vehicle) == PlayerId() then
Entity(vehicle).state:set('community_bridge:SetVehicleProperties', props, true)
if props.doorLockStatus then Entity(vehicle).state:set('door', tonumber(props.doorLockStatus), true) end
end
return true
end
return Vehicles
+1 -1
View File
@@ -43,7 +43,7 @@ function Clothing.GetAppearance(entity)
return skinData
end
Callback.Register('community_bridge:cb:GetAppearance', function()
lib.callback.register('community_bridge:cb:GetAppearance', function()
local ped = PlayerPedId()
if not ped or not DoesEntityExist(ped) then return end
local skinData = Clothing.GetAppearance(ped)
+1 -1
View File
@@ -22,7 +22,7 @@ end
---@param src number
---@return table
function Clothing.GetAppearance(src)
return Callback.Trigger('community_bridge:cb:GetAppearance', src)
return lib.callback.await('community_bridge:cb:GetAppearance', src)
end
---Apply skin data to a player
+1 -1
View File
@@ -147,7 +147,7 @@ function Clothing.OpenMenu(src)
end
---Callback handler for retrieving a player's appearance data
Callback.Register('community_bridge:cb:GetAppearance', function(source)
lib.callback.register('community_bridge:cb:GetAppearance', function(source)
local src = source
return Clothing.GetAppearance(src)
end)
+1 -1
View File
@@ -167,7 +167,7 @@ AddEventHandler('onResourceStart', function(resource)
end)
--- Callback handler for retrieving a player's appearance data
Callback.Register('community_bridge:cb:GetAppearance', function(source)
lib.callback.register('community_bridge:cb:GetAppearance', function(source)
local src = source
return Clothing.GetAppearance(src)
end)
@@ -160,7 +160,7 @@ AddEventHandler('onResourceStart', function(resource)
end)
--- Callback handler for retrieving a player's appearance data
Callback.Register('community_bridge:cb:GetAppearance', function(source)
lib.callback.register('community_bridge:cb:GetAppearance', function(source)
local src = source
return Clothing.GetAppearance(src)
end)
+1 -1
View File
@@ -168,7 +168,7 @@ AddEventHandler('onResourceStart', function(resource)
end)
--- Callback handler for retrieving a player's appearance data
Callback.Register('community_bridge:cb:GetAppearance', function(source)
lib.callback.register('community_bridge:cb:GetAppearance', function(source)
local src = source
return Clothing.GetAppearance(src)
end)
+2 -2
View File
@@ -11,7 +11,7 @@ local cachedItemList = nil
---@description This is an internal function, its here to attempt to emulate qbs shared items mainly. This should not be used outside of bridge.
Framework.ItemList = function()
if cachedItemList then return cachedItemList end
local items = Callback.Trigger('community_bridge:Callback:GetFrameworkItems', false)
local items = lib.callback.await('community_bridge:Callback:GetFrameworkItems', false)
cachedItemList = { Items = items.Items or {} }
return cachedItemList
end
@@ -45,7 +45,7 @@ end
---@description This will return a table of all the jobs in the framework.
---@return table
Framework.GetFrameworkJobs = function()
local jobs = Callback.Trigger('community_bridge:Callback:GetFrameworkJobs', false)
local jobs = lib.callback.await('community_bridge:Callback:GetFrameworkJobs', false)
return jobs
end
+93 -3
View File
@@ -69,6 +69,15 @@ Framework.GetPlayerDob = function(src)
return dob
end
Framework.GetPlayerDobByIdentifier = function(citizenid)
local xPlayer = Framework.GetPlayerByIdentifier(citizenid)
if xPlayer then
return xPlayer.get("dateofbirth")
end
local result = MySQL.single.await("SELECT dateofbirth FROM users WHERE identifier = @identifier", {["@identifier"] = citizenid})
return result and result.dateofbirth or nil
end
--- @description Returns the player data of the specified source in the framework defualt format
--- @param src any
--- @return table | nil
@@ -120,6 +129,15 @@ Framework.GetPlayerName = function(src)
return xPlayer.variables.firstName, xPlayer.variables.lastName
end
Framework.GetPlayerNameByIdentifier = function(citizenid)
local xPlayer = Framework.GetPlayerByIdentifier(citizenid)
if xPlayer then
return xPlayer.variables.firstName, xPlayer.variables.lastName
end
local result = MySQL.single.await("SELECT firstname, lastname FROM users WHERE identifier = @identifier", {["@identifier"] = citizenid})
return result and result.firstname or nil, result and result.lastname or nil
end
---@description This will return a table of all logged in players
--- @return table
Framework.GetPlayers = function()
@@ -340,6 +358,15 @@ Framework.GetPlayerPhone = function(src)
return xPlayer.get("phone_number")
end
Framework.GetPlayerPhoneByIdentifier = function(citizenid)
local xPlayer = Framework.GetPlayerByIdentifier(citizenid)
if xPlayer then
return xPlayer.get("phone_number")
end
local result = MySQL.single.await("SELECT phone_number FROM users WHERE identifier = @identifier", {["@identifier"] = citizenid})
return result and result.phone_number or nil
end
---@description This will return the job name, label, grade name, and grade level of the player.
---@deprecated
---@param src number
@@ -404,7 +431,10 @@ Framework.GetPlayerGang = function(src)
print("ESX does not support gangs, please ensure you are using a supported gang system or that you have the correct start order.")
return
end
Framework.GetPlayerGangByIdentifier = function(citizenid)
print("ESX does not support gangs, please ensure you are using a supported gang system or that you have the correct start order.")
return
end
---@description This will get a table of player sources that have the specified job name.
--- @param job string
--- @return table
@@ -441,6 +471,28 @@ Framework.AddAccountBalance = function(src, _type, amount)
return true
end
---@description This will add money based on the type of account (money/bank)
--- @param src number
--- @param _type string
--- @param amount number
--- @return boolean
Framework.AddAccountBalanceByIdentifier = function(src, _type, amount)
local xPlayer = Framework.GetPlayer(src)
if _type == 'cash' then _type = 'money' end
if amount <= 0 then return false end
if xPlayer then
xPlayer.addAccountMoney(_type, amount)
return true
end
local money = MySQL.single.await("SELECT accounts FROM users WHERE identifier = @identifier", {["@identifier"] = src})
if not money then return false end
local accounts = json.decode(money.accounts)
accounts[_type] = (accounts[_type] or 0) + amount
MySQL.update.await("UPDATE users SET accounts = @accounts WHERE identifier = @identifier", {["@accounts"] = json.encode(accounts), ["@identifier"] = src})
return true
end
---@description This will remove money based on the type of account (money/bank)
--- @param src number
--- @param _type string
@@ -457,6 +509,30 @@ Framework.RemoveAccountBalance = function(src, _type, amount)
return true
end
---@description This will remove money based on the type of account (money/bank)
--- @param src number
--- @param _type string
--- @param amount number
--- @return boolean
Framework.RemoveAccountBalanceByIdentifier = function(src, _type, amount)
local xPlayer = Framework.GetPlayer(src)
if _type == 'cash' then _type = 'money' end
if amount <= 0 then return false end
if xPlayer then
local accountVal = Framework.GetAccountBalance(src, _type)
if accountVal < amount then return false end
xPlayer.removeAccountMoney(_type, amount)
return true
end
local money = MySQL.single.await("SELECT accounts FROM users WHERE identifier = @identifier", {["@identifier"] = src})
if not money then return false end
local accounts = json.decode(money.accounts)
if (accounts[_type] or 0) < amount then return false end
accounts[_type] = (accounts[_type] or 0) - amount
MySQL.update.await("UPDATE users SET accounts = @accounts WHERE identifier = @identifier", {["@accounts"] = json.encode(accounts), ["@identifier"] = src})
return true
end
---@description This will get money based on the type of account (money/bank)
--- @param src number
--- @param _type string
@@ -470,6 +546,20 @@ Framework.GetAccountBalance = function(src, _type)
return balance
end
Framework.GetAccountBalanceByIdentifier = function(src, _type)
local xPlayer = Framework.GetPlayerByIdentifier(src)
if _type == 'cash' then _type = 'money' end
if xPlayer then
local balance = xPlayer.getAccount(_type).money or 0
if balance <= 0 then return 0 end
return balance
end
local money = MySQL.single.await("SELECT accounts FROM users WHERE identifier = @identifier", {["@identifier"] = src})
if not money then return 0 end
local accounts = json.decode(money.accounts)
return accounts[_type] or 0
end
---@description This will add an item, and return true or false based on success
--- This is an internal function and should not be used outside of bridge, use the Inventory module instead when dealing with items.
---@param src number
@@ -600,13 +690,13 @@ end)
---@description Callback to get framework jobs list
---@param source number
Callback.Register('community_bridge:Callback:GetFrameworkJobs', function(source)
lib.callback.register('community_bridge:Callback:GetFrameworkJobs', function(source)
return Framework.GetFrameworkJobs() or {}
end)
---@description This is linked to an internal function, its an attempt to standardize the item list across frameworks.
---@param source number
Callback.Register('community_bridge:Callback:GetFrameworkItems', function(source)
lib.callback.register('community_bridge:Callback:GetFrameworkItems', function(source)
return Framework.ItemList() or {}
end)
+87 -1
View File
@@ -4,7 +4,7 @@ if GetResourceState('qbx_core') == 'started' then return end
Framework = Framework or {}
QBCore = exports['qb-core']:GetCoreObject()
local QBCore = exports['qb-core']:GetCoreObject()
Framework.Shared = QBCore.Shared
@@ -93,6 +93,15 @@ Framework.GetPlayerName = function(src)
return playerData.charinfo.firstname, playerData.charinfo.lastname
end
---@description Returns the first and last name of the player.
---@return string|nil, string|nil
Framework.GetPlayerNameByIdentifier = function(id)
local player = Framework.GetPlayerByIdentifier(id) or QBCore.Functions.GetOfflinePlayer(id)
if not player then return end
local playerData = player.PlayerData
return playerData.charinfo.firstname, playerData.charinfo.lastname
end
---@description Returns the player date of birth.
---@param src number
---@return string|nil
@@ -103,6 +112,17 @@ Framework.GetPlayerDob = function(src)
return playerData.charinfo.birthdate
end
---@description Returns the player date of birth.
---@param id number
---@return string|nil
Framework.GetPlayerDobByIdentifier = function(id)
local player = Framework.GetPlayerByIdentifier(id) or QBCore.Functions.GetOfflinePlayer(id)
if not player then return end
local playerData = player.PlayerData
return playerData.charinfo.birthdate
end
---@description Returns a table of items matching the specified name and if passed metadata from the player's inventory.
---@param src number
---@param item string
@@ -240,6 +260,7 @@ Framework.SetPlayerMetadata = function(src, metadata, value)
return true
end
---@description Gets the specified metadata key to the player's data.
---@param src number
---@param metadata string
@@ -370,6 +391,17 @@ Framework.GetPlayerPhone = function(src)
return playerData.charinfo.phone
end
---@description Returns the phone number of the player.
---@param src number
---@return string | nil
Framework.GetPlayerPhoneByIdentifier = function(src)
local player = Framework.GetPlayerByIdentifier(src) or QBCore.Functions.GetOfflinePlayer(src)
if not player then return end
local playerData = player.PlayerData
return playerData.charinfo.phone
end
---@description Returns the gang name of the player.
---@param src number
---@return string | nil
@@ -380,6 +412,16 @@ Framework.GetPlayerGang = function(src)
return playerData.gang.name
end
---@description Returns the gang name of the player.
---@param id number
---@return string | nil
Framework.GetPlayerGangByIdentifier = function(id)
local player = Framework.GetPlayerByIdentifier(id) or QBCore.Functions.GetOfflinePlayer(id)
if not player then return end
local playerData = player.PlayerData
return playerData.gang.name
end
---@description This will get a table of player sources that have the specified job name.
---@param job string
---@return table
@@ -400,6 +442,8 @@ Framework.GetPlayerJob = function(src)
return jobData.jobName, jobData.jobLabel, jobData.gradeName, jobData.gradeLevel
end
---@description This will return the players job name, job label, job grade label job grade level, boss status,
---and duty status in a table
---@param src number
@@ -467,6 +511,24 @@ Framework.AddAccountBalance = function(src, _type, amount)
return player.Functions.AddMoney(_type, amount)
end
---@description This will add money based on the type of account (money/bank)
---@param src number
---@param _type string
---@param amount number
---@return boolean | nil
Framework.AddAccountBalanceByIdentifier = function(id, _type, amount)
local player = Framework.GetPlayerByIdentifier(id) or QBCore.Functions.GetOfflinePlayer(id)
if not player then return false end
if _type == 'money' then _type = 'cash' end
if amount <= 0 then return false end
local paid = player.Functions.AddMoney(_type, amount)
if paid and not player.PlayerData.source then
player.Functions.Save()
end
return paid
end
---@description This will remove money based on the type of account (money/bank)
---@param src number
---@param _type string
@@ -479,6 +541,22 @@ Framework.RemoveAccountBalance = function(src, _type, amount)
return player.Functions.RemoveMoney(_type, amount)
end
---@description This will remove money based on the type of account (money/bank)
---@param src number
---@param _type string
---@param amount number
---@return boolean | nil
Framework.RemoveAccountBalanceByIdentifier = function(id, _type, amount)
local player = Framework.GetPlayerByIdentifier(id) or QBCore.Functions.GetOfflinePlayer(id)
if not player then return false end
if _type == 'money' then _type = 'cash' end
local paid = player.Functions.RemoveMoney(_type, amount)
if paid and not player.PlayerData.source then
player.Functions.Save()
end
return paid
end
---@description This will remove money based on the type of account (money/bank)
---@param src number
---@param _type string
@@ -491,6 +569,14 @@ Framework.GetAccountBalance = function(src, _type)
return playerData.money[_type]
end
Framework.GetAccountBalanceByIdentifier = function(id, _type)
local player = Framework.GetPlayerByIdentifier(id) or QBCore.Functions.GetOfflinePlayer(id)
if not player then return 0 end
local playerData = player.PlayerData
if _type == 'money' then _type = 'cash' end
return playerData.money[_type]
end
---@description This will add an item, and return true or false based on success
---This is an internal function and should not be used outside of bridge, use the Inventory module instead when dealing with items.
---@param src number
+90
View File
@@ -35,6 +35,17 @@ Framework.GetPlayerDob = function(src)
return playerData.charinfo.birthdate
end
---@description Returns the player date of birth.
---@param id string
---@return string|nil
Framework.GetPlayerDobByIdentifier = function(id)
local player = Framework.GetPlayerByIdentifier(id) or QBox:GetOfflinePlayer(id)
if not player then return end
local playerData = player.PlayerData
return playerData.charinfo.birthdate
end
---@description Returns the player data of the specified source.
---@param src any
---@return table | nil
@@ -102,6 +113,17 @@ Framework.GetPlayerName = function(src)
return playerData.charinfo.firstname, playerData.charinfo.lastname
end
---@description Returns the first and last name of the player.
---@param src number
---@return string | nil
---@return string | nil
Framework.GetPlayerNameByIdentifier = function(src)
local player = Framework.GetPlayerByIdentifier(src) or QBox:GetOfflinePlayer(src)
if not player then return end
local playerData = player.PlayerData
return playerData.charinfo.firstname, playerData.charinfo.lastname
end
---@description Adds the specified item to the player's inventory.
---This is an internal function and should not be used outside of bridge, use the Inventory module instead when dealing with items.
---@param src number
@@ -350,6 +372,17 @@ Framework.GetPlayerPhone = function(src)
return playerData.charinfo.phone
end
---@description Returns the phone number of the player.
---@param src number
---@return string | nil
Framework.GetPlayerPhoneByIdentifier = function(src)
local player = Framework.GetPlayerByIdentifier(src) or QBox:GetOfflinePlayer(src)
if not player then return end
local playerData = player.PlayerData
return playerData.charinfo.phone
end
---@description Returns the gang name of the player.
---@param src number
---@return string | nil
@@ -358,6 +391,17 @@ Framework.GetPlayerGang = function(src)
return player.gang.name
end
---@description Returns the gang name of the player.
---@param id number
---@return string | nil
Framework.GetPlayerGangByIdentifier = function(id)
local player = Framework.GetPlayerByIdentifier(id) or QBox:GetOfflinePlayer(id)
if not player then return end
local playerData = player.PlayerData
return playerData.gang.name
end
---@description This will get a table of player sources that have the specified job name.
---@param job string
---@return table
@@ -445,6 +489,24 @@ Framework.AddAccountBalance = function(src, _type, amount)
return player.Functions.AddMoney(_type, amount)
end
---@description Adds the specified amount to the player's account balance of the specified type.
---@param id string
---@param _type string
---@param amount number
---@return boolean | nil
Framework.AddAccountBalanceByIdentifier = function(id, _type, amount)
local player = Framework.GetPlayerByIdentifier(id) or QBox:GetOfflinePlayer(id)
if not player then return end
if _type == 'money' then _type = 'cash' end
if amount <= 0 then return false end
local paid = player.Functions.AddMoney(_type, amount)
if paid and not player.PlayerData.source then
QBox:SaveOffline(player.PlayerData)
end
return paid
end
---@description Removes the specified amount from the player's account balance of the specified type.
---@param src number
---@param _type string
@@ -458,6 +520,22 @@ Framework.RemoveAccountBalance = function(src, _type, amount)
return player.Functions.RemoveMoney(_type, amount)
end
---@description This will remove money based on the type of account (money/bank)
---@param src number
---@param _type string
---@param amount number
---@return boolean | nil
Framework.RemoveAccountBalanceByIdentifier = function(id, _type, amount)
local player = Framework.GetPlayerByIdentifier(id) or QBox:GetOfflinePlayer(id)
if not player then return false end
if _type == 'money' then _type = 'cash' end
local paid = player.Functions.RemoveMoney(_type, amount)
if paid and not player.PlayerData.source then
QBox:SaveOffline(player.PlayerData)
end
return paid
end
---@description Returns the player's account balance of the specified type.
---@param src number
---@param _type string
@@ -472,6 +550,18 @@ Framework.GetAccountBalance = function(src, _type)
return balance
end
---@description Returns the player's account balance of the specified type.
---@param id string
---@param _type string
---@return number | nil
Framework.GetAccountBalanceByIdentifier = function(id, _type)
local player = Framework.GetPlayerByIdentifier(id) or QBox:GetOfflinePlayer(id)
if not player then return 0 end
local playerData = player.PlayerData
if _type == 'money' then _type = 'cash' end
return playerData.money[_type]
end
---@description Returns a table of owned vehicles for the player. format is {vehicle = vehicle, plate = plate}
---@param src number
---@return table
+1 -1
View File
@@ -6,7 +6,7 @@ Menu = {}
---@param useQb boolean Whether to use QB menu syntax.
---@return id string The menu ID.
function Menu.Open(data, useQb)
local id = data.id or Ids.CreateUniqueId(Menus, nil, nil)
local id = data.id or lib.string.random('Aa1A', 8) -- Generate a random ID if not provided
Menus[id] = OpenMenu(id, data, useQb)
data.id = id
return id
+1 -1
View File
@@ -20,7 +20,7 @@ end
---@param message string
---@return boolean
Phone.SendEmail = function(email, title, message)
local success = Callback.Trigger('community_bridge:Callback:okokPhone:sendEmail', false, email, title, message)
local success = lib.callback.await('community_bridge:Callback:okokPhone:sendEmail', false, email, title, message)
return success
end
+1 -1
View File
@@ -58,7 +58,7 @@ Phone.SendEmail = function(src, email, title, message)
return success
end
Callback.Register('community_bridge:Callback:okokPhone:sendEmail', function(src, email, title, message)
lib.callback.register('community_bridge:Callback:okokPhone:sendEmail', function(src, email, title, message)
return Phone.SendEmail(src, email, title, message)
end)
+2 -2
View File
@@ -21,7 +21,7 @@ end)
Shops.FinalizeCheckOut = function(shopName, item, itemLabel, price, amount)
if not shopName and not item and not itemLabel and not price then return end
local mathStuff = (tonumber(price) * tonumber(amount))
local generatedID = Ids.CreateUniqueId()
local generatedID = lib.string.random('Aa1A', 8) -- Generate a random ID if not provided
local buildMenu = {
{
title = locale('Shops.PayByCash', tostring(mathStuff)),
@@ -72,7 +72,7 @@ end
---@return nil
Shops.OpenShop = function(shopName, shopData)
if not shopName and not shopData then return print("^6 No Shop Name or Shop Data Passed ^0") end
local generatedID = Ids.CreateUniqueId()
local generatedID = lib.string.random('Aa1A', 8) -- Generate a random ID if not provided
local buildMenu = {}
for _, v in pairs(shopData) do
local getItemName = Inventory.GetItemInfo(v.name).label
+5 -3
View File
@@ -1,4 +1,6 @@
---@diagnostic disable: duplicate-set-field
---
---TODO: fix points
Target = Target or {}
Ids = Ids or Require("lib/utility/shared/ids.lua")
@@ -18,7 +20,7 @@ end
function Target.CreateCanInteract(cb)
if not cb then return end
local id = Ids.CreateUniqueId(InteractIds)
local id = lib.string.random('Aa1A', 8) -- Generate a random ID if not provided
InteractIds[id] = {
id = id,
ableToInteract = -1,
@@ -80,7 +82,7 @@ function Target.AddLocalEntity(entities, _options)
entities = { entities }
end
for _, entity in pairs(entities) do
local id = Ids.RandomString()
local id = lib.string.random('Aa1A', 8) -- Generate a random ID if not provided
local title = Language.Locale("target.title")
local menuData = { id = id, title = title, options = {} }
for k, v in pairs(fixedOptions) do
@@ -128,7 +130,7 @@ end
function Target.AddBoxZone(name, coords, size, heading, options)
local fixedOptions = Target.FixOptions(options)
local id = Ids.RandomString()
local id = lib.string.random('Aa1A', 8) -- Generate a random ID if not provided
local title = Bridge.Language.Locale("target.title")
local menuData = { id = id, title = title, options = {} }
for k, v in pairs(fixedOptions) do
-161
View File
@@ -1,161 +0,0 @@
--- ox_lib compatibility wrapper for zone creation and management.
--- Provides a small API around lib.zones (box, sphere, poly) to create/destroy
--- and lookup zones with automatic id generation and resource ownership.
---
--- Example:
--- local id = cZones.Create("box", { coords = vec3(0,0,0), size = vec3(2,2,2), onEnter = function(z) ... end })
--- cZones.Destroy(id)
---
---@module cZones
---@class ZoneData
---@field id string Unique id for the zone (generated)
---@field invoking string Resource that created the zone
---@field coords vector3? Center coordinates (box/sphere)
---@field points vector2[]? Array of points for poly zones
---@field radius number? Radius for sphere zones
---@field size table? Size table or vec3 for box zones
---@field zone any Internal zone handle returned by lib.zones
---@field debug boolean? Debug flag passed to lib.zones
---@field onEnter fun(data:ZoneData)? Callback invoked on enter (receives ZoneData)
---@field onExit fun(data:ZoneData)? Callback invoked on exit (receives ZoneData)
---@alias ZoneType "box"|"sphere"|"poly"
---@diagnostic disable: duplicate-set-field
local resourceName = "ox_lib"
if GetResourceState(resourceName) == 'missing' then return end
if not lib then Require('init.lua', 'ox_lib') end
Ids = Ids or Require('lib/utility/shared/ids.lua')
cZones = {} --conflict with ox
cZones.All = {}
--- Create a zone of the specified type.
--- Supported types: "box", "sphere", "poly"
---@param type ZoneType
---@param data ZoneData
---@return string|nil id Returns the generated zone id on success, or nil on failure
function cZones.Create(type, data)
assert(type, "Requires zone type ('box', 'sphere', or 'poly')")
assert(data, "Requires data table")
data.id = Ids.CreateUniqueId(cZones.All)
data.invoking = GetInvokingResource() or "unknown"
local onEnter = data.onEnter or data.OnEnter
local onExit = data.onExit or data.OnExit
local zone = nil
if type == "box" then
assert(data.coords, "Requires .coords as vector3 in data")
local width = data.size?.x or data.length or 1.0
local height = data.size?.y or data.width or 1.0
local z = data.size?.z or data.height or 1.0
zone = lib.zones.box({
coords = data.coords,
size = vec3(width, height, z),
rotation = data.heading or data.rotation or 0.0,
debug = data.debug or false,
onEnter = function(point)
if onEnter then
onEnter(data)
end
end,
onExit = function(point)
if onExit then
onExit(data)
end
end,
})
data.zone = zone
print("Created Zone: " .. data.id, json.encode(cZones.All))
cZones.All[data.id] = data
return data.id
elseif type == "sphere" then
assert(data.coords, "Requires .coords as vector3 in data")
data.radius = data.radius or data.size?.x or 1
lib.zones.sphere(data)
local zone = lib.zones.sphere({
coords = data.coords,
radius = data.radius,
debug = data.debug or false,
onEnter = function(point)
data.zone = data.zone or point
if onEnter then
onEnter(data)
end
end,
onExit = function(point)
data.zone = data.zone or point
if onExit then
onExit(data)
end
end,
})
data.zone = zone
cZones.All[data.id] = data
return data.id
elseif type == "poly" then
assert(data.points, "Requires an array of vector2 in .points")
assert(#data.points > 2, "Requires at least three points in .points")
local zSize = data.minZ or data.size?.z or data.height or data.thickness or 2
local polyZone = lib.zones.poly({
points = data.points,
thickness = zSize,
debug = data.debug or false,
onEnter = function(point)
data.zone = data.zone or point
if onEnter then
onEnter(data)
end
end,
onExit = function(point)
data.zone = data.zone or point
if onExit then
onExit(data)
end
end,
})
data.zone = polyZone
cZones.All[data.id] = data
return data.id
end
return nil
end
--- Destroy a zone by id.
---@param id string
---@return boolean success True if destroyed, false otherwise
function cZones.Destroy(id)
if not id then return false end
local zone = cZones.All[id].zone
if not zone then return false end
zone:remove()
cZones.All[id] = nil
return true
end
--- Destroy all zones created by a specific resource.
---@param resource string Name of the invoking resource
---@return boolean success True if operation completed (no guarantee zones existed)
function cZones.DestroyByResource(resource)
if not resource then return false end
for id, zone in pairs(cZones.All or {}) do
if zone.invoking == resource then
zone.zone:remove()
end
end
return true
end
--- Retrieve zone data by id.
---@param id string
---@return ZoneData|nil
function cZones.Get(id)
if not id then return nil end
return cZones.All[id]
end
--- Event handler: clean up zones when a resource stops.
--- This is registered to the "onResourceStop" event and delegates to DestroyByResource.
RegisterNetEvent("onResourceStop", function(resource)
cZones.DestroyByResource(resource)
end)
-116
View File
@@ -1,116 +0,0 @@
---@diagnostic disable: duplicate-set-field
local resourceName = "PolyZone"
if GetResourceState(resourceName) == 'missing' or GetResourceState('ox_lib') ~= 'missing' then return end
Require("client.lua", resourceName)
Require("BoxZone.lua", resourceName)
Require("EntityZone.lua", resourceName)
Require("CircleZone.lua", resourceName)
Require("ComboZone.lua", resourceName)
Ids = Ids or Require('lib/utility/shared/ids.lua')
cZones = {
All = {}
}
--- Create a zone of the specified type.
--- Supported types: "box", "sphere", "poly"
---@param type ZoneType
---@param data ZoneData
---@return string|nil id Returns the generated zone id on success, or nil on failure
function cZones.Create(type, data)
assert(type, "Requires zone type ('box', 'sphere', or 'poly')")
assert(data, "Requires data table")
data.id = Ids.CreateUniqueId(cZones.All)
data.invoking = GetInvokingResource() or "unknown"
local zone = nil
if type == "box" then
assert(data.coords, "Requires .coords as vector3 in data")
local width = data.size.x or data.length or 1.0
local height = data.size.y or data.width or 1.0
local z = data.size?.z or data.height or 1.0
data.size = vec3(width, height, z)
data.heading = data.heading or data.rotation
data.rotation = data.heading
zone = BoxZone:Create(data.coords, width, height, {
name = data.id,
debugPoly = data.debug,
minZ = data.coords.z - 0.5,
maxZ = data.coords.z + z - 0.5,
heading = data.heading or data.rotation
})
elseif type == "sphere" then
assert(data.coords, "Requires .coords as vector3 in data")
data.radius = data.radius or data.size?.x or 1
zone = CircleZone:Create(data.coords, data.radius, {
name = data.id,
debugPoly = data.debug,
})
elseif type == "poly" then
assert(data.points, "Requires an array of vector2 in .points")
assert(#data.points > 2, "Requires at least three points in .points")
local zSize = data.minZ or data.size?.z or data.height or data.thickness or 2
local firstPoint = data.points[1]
local firstZ = firstPoint.z
zone = PolyZone:Create(data.points, {
name = data.id,
debugPoly = data.debug,
minZ = firstZ - 0.5,
maxZ = firstZ and (firstZ + zSize - 0.5) or nil,
})
end
if not zone then return end
data.zone = zone
zone:onPlayerInOut(function(isInside, _)
if isInside then
if data.onEnter or data.OnEnter then
(data.onEnter or data.OnEnter)(data)
end
else
if data.onExit or data.OnExit then
(data.onExit or data.OnExit)(data)
end
end
end)
cZones.All[data.id] = data
return data.id
end
--- Destroy a zone by id.
---@param id string
---@return boolean success True if destroyed, false otherwise
function cZones.Destroy(id)
if not id then return false end
local zone = cZones.All[id].zone
if not zone then return false end
zone:destroy()
cZones.All[id] = nil
return true
end
--- Destroy all zones created by a specific resource.
---@param resource string Name of the invoking resource
---@return boolean success True if operation completed (no guarantee zones existed)
function cZones.DestroyByResource(resource)
if not resource then return false end
for id, zone in pairs(cZones.All) do
if zone.invoking == resource then
zone.zone:destroy()
end
end
return true
end
--- Retrieve zone data by id.
---@param id string
---@return ZoneData|nil
function cZones.Get(id)
if not id then return nil end
return cZones.All[id]
end
--- Event handler: clean up zones when a resource stops.
---@param resource string
RegisterNetEvent("onResourceStop", function(resource)
cZones.DestroyByResource(resource)
end)
+31
View File
@@ -0,0 +1,31 @@
Overall Community Bridge has been a blessing to fivem and a lot of creators, but i know people are becoming more and more wary to actually utilizing this because the scope has
since lost its way. over complicated library modules have led to bloatware where we dont need bloat. since ox_lib is required to run the bridge, why try to re-invent the wheel
of a great library already and include it in a "bridge"
Since I personally believe that we should have a much more narrow scope I decided to do some leg work and reduce the lib modules to things that are **needed** and **not already handled by ox_lib**
# Completely Removed | Lib
1) lib/anim module
- this already exists inside of ox_lib. there is no use for it.
- its only called in entities/client/client_entity so if that module stays it will be replaced with ox's call
2) callback
- while I do enjoy these callbacks, theres no specific reason to keep these involved as ox already exists in this repo by requiring it
- all modules that used callbacks are easily switched to ox callbacks
3) markers
- while a neat module, ox does this
4) points as well as you can really just use ox zones. may not be a 1 for 1, but ox zones can accomplish the same things
5) raycast is already handled with ox lib
6) scaleform already handled with ox_lib
7) shells is pointless, if anything the script should be doing the spawning and handling and not a bridge. as many different shells from different creators exits
8) sql is a wrapper of a wrapper for mysql, every framework starts with oxmysql, while an ORM would be nice, this isnt ORM level yet
9) vehicles is not needed as ox handles this
10) cutscenes
- like why? its used in so little of resources, no sense of keep loading this everywhere
# Completely Removed | modules
1) zones
- lets face it, polyzone is fucking trash and hasnt been given a semi decent update in 5 years. ox_lib is required for this bridge so we should enforce higher code quality
and there isnt a need for a wrapper when its a single resource being used, i can see this coming back in the future if someone makes a better or comparable zone