From 3cb9829f4f5f723569378b66cc970b943cc3d22a Mon Sep 17 00:00:00 2001 From: gononono64 <96976330+gononono64@users.noreply.github.com> Date: Sun, 4 May 2025 11:06:55 -0500 Subject: [PATCH 01/15] Qs-inventory and Framework IsPlayerDead fixes qs item info had typo. IsPlayerDead was missing last stand for qb also removed couple debug prints --- modules/framework/qb-core/server.lua | 2 +- modules/inventory/origen_inventory/server.lua | 1 - modules/inventory/ox_inventory/server.lua | 1 - modules/inventory/qs-inventory/client.lua | 7 ++++--- modules/inventory/qs-inventory/server.lua | 6 ++++-- 5 files changed, 9 insertions(+), 8 deletions(-) diff --git a/modules/framework/qb-core/server.lua b/modules/framework/qb-core/server.lua index 98a52a8..6146517 100644 --- a/modules/framework/qb-core/server.lua +++ b/modules/framework/qb-core/server.lua @@ -257,7 +257,7 @@ Framework.GetIsPlayerDead = function(src) local player = QBCore.Functions.GetPlayer(src) if not player then return end local playerData = player.PlayerData - return playerData.metadata.isdead or false + return playerData.metadata.isdead or playerData.metadata.inlaststand or false end diff --git a/modules/inventory/origen_inventory/server.lua b/modules/inventory/origen_inventory/server.lua index 4bc27d4..f567fb9 100644 --- a/modules/inventory/origen_inventory/server.lua +++ b/modules/inventory/origen_inventory/server.lua @@ -55,7 +55,6 @@ Inventory.GetPlayerInventory = function(src) local playerItems = origen_inventory:GetInventory(src) local repackedTable = {} for _, v in pairs(playerItems.inventory) do - print(json.encode(v, { indent = true })) table.insert(repackedTable, { name = v.name, count = v.count, diff --git a/modules/inventory/ox_inventory/server.lua b/modules/inventory/ox_inventory/server.lua index f277fa0..e2eb791 100644 --- a/modules/inventory/ox_inventory/server.lua +++ b/modules/inventory/ox_inventory/server.lua @@ -150,7 +150,6 @@ end ---@return string Inventory.GetImagePath = function(item) item = Inventory.StripPNG(item) - print(item) local file = LoadResourceFile("ox_inventory", string.format("web/images/%s.png", item)) local imagePath = file and string.format("nui://ox_inventory/web/images/%s.png", item) return imagePath or "https://avatars.githubusercontent.com/u/47620135" diff --git a/modules/inventory/qs-inventory/client.lua b/modules/inventory/qs-inventory/client.lua index 91a1671..9a0f0d1 100644 --- a/modules/inventory/qs-inventory/client.lua +++ b/modules/inventory/qs-inventory/client.lua @@ -1,6 +1,5 @@ if GetResourceState('qs-inventory') ~= 'started' then return end local quasar = exports["qs-inventory"] - Inventory = Inventory or {} ---comment @@ -14,8 +13,10 @@ end ---@param item string ---@return table Inventory.GetItemInfo = function(item) - local itemData = quasar:GetItemList() - if not itemData[item] then return {} end + local itemsData = quasar:GetItemList() + if not itemsData then return {} end + local itemData = itemsData[item] + if not itemData then return {} end local repackedTable = { name = itemData.name or "Missing Name", label = itemData.label or "Missing Label", diff --git a/modules/inventory/qs-inventory/server.lua b/modules/inventory/qs-inventory/server.lua index 699917f..0cbc1a8 100644 --- a/modules/inventory/qs-inventory/server.lua +++ b/modules/inventory/qs-inventory/server.lua @@ -127,8 +127,10 @@ end ---@param item string ---@return table Inventory.GetItemInfo = function(item) - local itemData = quasar:GetItemList() - if not itemData[item] then return {} end + local itemsData = quasar:GetItemList() + if not itemsData then return {} end + local itemData = itemsData[item] + if not itemData then return {} end local repackedTable = { name = itemData.name or "Missing Name", label = itemData.label or "Missing Label", From 4d8b2ff2032123ddb312d7c4aded334013314a9b Mon Sep 17 00:00:00 2001 From: gononono64 <96976330+gononono64@users.noreply.github.com> Date: Sun, 4 May 2025 11:11:29 -0500 Subject: [PATCH 02/15] Rebound entity stuff added function to get a local offset world position from a point updated entities to automatically process next queued action without needing to call processnextaction Added client freeze, circle, and bobupanddown for client/rebound entity manipulation --- lib/entities/client/client_entity.lua | 24 +++++ lib/entities/client/client_entity_actions.lua | 13 ++- .../client/client_entity_actions_ext.lua | 96 ++++++++++++++++++- lib/entities/server/server_entity.lua | 11 ++- lib/utility/shared/math.lua | 41 +++++++- 5 files changed, 174 insertions(+), 11 deletions(-) diff --git a/lib/entities/client/client_entity.lua b/lib/entities/client/client_entity.lua index 751f6e0..59af37b 100644 --- a/lib/entities/client/client_entity.lua +++ b/lib/entities/client/client_entity.lua @@ -156,6 +156,10 @@ function ClientEntity.GetAll() return Entities end +function ClientEntity.RegisterAction(name, func) + ClientEntityActions.RegisterAction(name, func) +end + -- Network Event Handlers RegisterNetEvent("community_bridge:client:CreateEntity", function(entityData) ClientEntity.Register(entityData) @@ -190,6 +194,26 @@ RegisterNetEvent("community_bridge:client:TriggerEntityAction", function(entityI end end) +RegisterNetEvent("community_bridge:client:TriggerEntityActions", function(entityId, actions, endPosition) + local entityData = Entities[entityId] + if entityData then + for _, actionData in pairs(actions) do + local actionName = actionData.name + local actionParams = actionData.params + if actionName == "Stop" then + ClientEntityActions.StopAction(entityId) + elseif actionName == "Skip" then + ClientEntityActions.SkipAction(entityId) + else + local currentAction = ClientEntityActions.ActionQueue[entityId] and ClientEntityActions.ActionQueue[entityId][1] + ClientEntityActions.QueueAction(entityData, actionName, table.unpack(actionParams)) + end + end + else + print(string.format("[ClientEntity] Received actions for non-existent entity %s.", entityId)) + end +end) + -- Resource Stop Cleanup AddEventHandler('onResourceStop', function(resourceName) if resourceName == GetCurrentResourceName() then diff --git a/lib/entities/client/client_entity_actions.lua b/lib/entities/client/client_entity_actions.lua index 9cf9f1e..b8ffd67 100644 --- a/lib/entities/client/client_entity_actions.lua +++ b/lib/entities/client/client_entity_actions.lua @@ -32,11 +32,16 @@ function ClientEntityActions.ProcessNextAction(entityId) -- print(string.format("[ClientEntityActions] Starting action '%s' for entity %s", nextAction.name, entityId)) ClientEntityActions.IsActionRunning [entityId] = true -- Call the registered function - actionFunc(entityData, table.unpack(nextAction.args)) + ClientEntityActions.ActionQueue[entityId] = actionFunc(entityData, table.unpack(nextAction.args)) + if not ClientEntityActions.ActionQueue[entityId] then + -- If the action function doesn't return a queue, set it to nil + ClientEntityActions.IsActionRunning[entityId] = false + ClientEntityActions.ProcessNextAction(entityId) -- Try next action if this one failed immediately + end else print(string.format("[ClientEntityActions] Unknown action '%s' dequeued for entity %s", nextAction.name, entityId)) -- Skip unknown action and try the next one immediately - ClientEntityActions.ProcessNextAction(entityId) + ClientEntityActions.ActionQueue[entityId] = ClientEntityActions.ProcessNextAction(entityId) end end --- Registers a custom action implementation. @@ -50,9 +55,7 @@ function ClientEntityActions.RegisterAction(actionName, actionFunc) print(string.format("[ClientEntityActions] WARNING: Overwriting registered action '%s'", actionName)) end assert(type(actionName) == "string", "actionName must be a string") - assert(type(actionFunc) == "function", "actionFunc must be a function") - print(string.format("[ClientEntityActions] Registered action: %s", actionName)) - ClientEntityActions.RegisteredActions [actionName] = actionFunc + ClientEntityActions.RegisteredActions[actionName] = actionFunc -- print(string.format("[ClientEntityActions] Registered action: %s", actionName)) end diff --git a/lib/entities/client/client_entity_actions_ext.lua b/lib/entities/client/client_entity_actions_ext.lua index 99622f2..73dc7b5 100644 --- a/lib/entities/client/client_entity_actions_ext.lua +++ b/lib/entities/client/client_entity_actions_ext.lua @@ -1,5 +1,7 @@ DefaultActions = {} -ClientEntityActions = ClientEntityActions or Require("lib/entities/client/client_entity_actions.lua") -- Added +ClientEntityActions = ClientEntityActions or Require("lib/entities/client/client_entity_actions.lua") +LA = LA or Require("lib/utility/shared/la.lua") + --- Internal implementation for walking. Registered via RegisterAction. function DefaultActions.WalkTo(entityData, coords, speed, timeout) print("[ClientEntityActions] WalkTo action called", coords, speed, timeout) @@ -196,7 +198,8 @@ function DefaultActions.AttachProp(entityData, propModel, boneName, offsetPos, o offsetRot = offsetRot or vector3(0.0, 0.0, 0.0) print(string.format("[ClientEntityActions] Attaching prop '%s' to entity %s at bone %d", propModel, entityId, boneIndex)) AttachEntityToEntity(prop, entity, boneIndex, offsetPos.x, offsetPos.y, offsetPos.z, offsetRot.x, offsetRot.y, offsetRot.z, false, useSoftPinning or false, collision or false, isPed or false, vertexIndex or 2, fixedRot == nil and true or fixedRot) - + entityData.props = entityData.props or {} -- Ensure props table exists + table.insert(entityData.props, prop) -- Store the prop handle in the entity data -- Store the attached prop handle for later removal if not entityData.attachedProps then entityData.attachedProps = {} end entityData.attachedProps[propModel] = prop -- Store by model name/hash for easy lookup @@ -226,8 +229,8 @@ function DefaultActions.DetachProp(entityData, propModel) end -- This action finishes immediately - ClientEntityActions.IsActionRunning[entityId] = false - ClientEntityActions.ProcessNextAction(entityId) + -- ClientEntityActions.IsActionRunning[entityId] = false + -- ClientEntityActions.ProcessNextAction(entityId) end function DefaultActions.GetInCar(entityData, vehicleData, seatIndex, timeout) @@ -264,8 +267,93 @@ function DefaultActions.GetInCar(entityData, vehicleData, seatIndex, timeout) ClientEntityActions.ActionThreads[entityId] = thread end +function DefaultActions.Freeze(entityData, freeze) + print("[ClientEntityActions] Freeze action called", freeze) + local entity = entityData.spawned + local entityId = entityData.id + + if not entity or not DoesEntityExist(entity) then + ClientEntityActions.IsActionRunning[entityId] = false + ClientEntityActions.ProcessNextAction(entityId) -- Try next action if this one failed immediately + return + end + + FreezeEntityPosition(entity, freeze or true) + + -- This action finishes immediately + ClientEntityActions.IsActionRunning[entityId] = false + ClientEntityActions.ProcessNextAction(entityId) +end + +function DefaultActions.PlaceOnGround(entityData) + local entity = entityData.spawned + local entityId = entityData.id + + if not entity or not DoesEntityExist(entity) then + ClientEntityActions.IsActionRunning[entityId] = false + ClientEntityActions.ProcessNextAction(entityId) -- Try next action if this one failed immediately + return + end + PlaceObjectOnGroundProperly(entity) + + -- This action finishes immediately + -- ClientEntityActions.IsActionRunning[entityId] = false + -- ClientEntityActions.ProcessNextAction(entityId) +end + +function DefaultActions.BobUpAndDown(entityData, speed, height) + local entity = entityData.spawned + local entityId = entityData.id + if not entity or not DoesEntityExist(entity) then + ClientEntityActions.IsActionRunning[entityId] = false + ClientEntityActions.ProcessNextAction(entityId) -- Try next action if this one failed immediately + return + end + CreateThread(function() + local coords = GetEntityCoords(entity) + local originalZ = coords.z + while DoesEntityExist(entity) do + -- Calculate the new Z coordinate + local newZ = originalZ + math.sin(GetGameTimer() * (speed / 1000)) * height + -- Set the new coordinates + SetEntityCoords(entity, coords.x, coords.y, newZ) + -- Wait for 10 milliseconds + Wait(10) + end + end) + -- ClientEntityActions.IsActionRunning[entityId] = false + -- ClientEntityActions.ProcessNextAction(entityId) -- Try next action if this one failed immediately +end + +function DefaultActions.Circle(entityData, radius, speed) + local entity = entityData.spawned + local entityId = entityData.id + + if not entity or not DoesEntityExist(entity) then + ClientEntityActions.IsActionRunning[entityId] = false + ClientEntityActions.ProcessNextAction(entityId) -- Try next action if this one failed immediately + return + end + + local coords = GetEntityCoords(entity) + local angle = 0.0 + CreateThread(function() + while DoesEntityExist(entity) do + FreezeEntityPosition(entity, false) + local pos = LA.Circle(angle, radius, coords) + SetEntityCoords(entity, pos.x, pos.y, pos.z, false, false, false, false) + angle = angle + speed * GetFrameTime() + FreezeEntityPosition(entity, true) + Wait(0) + end + end) + -- ClientEntityActions.IsActionRunning[entityId] = false + -- ClientEntityActions.ProcessNextAction(entityId) -- Try next action if this one failed immediately +end + for name, func in pairs(DefaultActions) do ClientEntityActions.RegisterAction(name, func) end + return ClientEntityActions diff --git a/lib/entities/server/server_entity.lua b/lib/entities/server/server_entity.lua index b040332..f066bbd 100644 --- a/lib/entities/server/server_entity.lua +++ b/lib/entities/server/server_entity.lua @@ -26,6 +26,7 @@ function ServerEntity.Create(id, entityType, model, coords, rotation, meta) ServerEntity.Add(self) TriggerClientEvent("community_bridge:client:CreateEntity", -1, self) + Wait(1000) return self end @@ -65,10 +66,18 @@ function ServerEntity.TriggerAction(entityId, actionName, endPosition, ...) print(string.format("[ServerEntity] Attempted to trigger action '%s' on non-existent entity %s", actionName, entityId)) return end - print(string.format("[ServerEntity] Triggering action '%s' for entity %s", actionName, entityId)) TriggerClientEvent("community_bridge:client:TriggerEntityAction", -1, entityId, actionName, endPosition, ...) end +function ServerEntity.TriggerActions(entityId, actions, endPosition) + local entity = Entities[entityId] + if not entity then + print(string.format("[ServerEntity] Attempted to trigger actions on non-existent entity %s", entityId)) + return + end + TriggerClientEvent("community_bridge:client:TriggerEntityActions", -1, entityId, actions, endPosition) +end + function ServerEntity.GetAll() return Entities end diff --git a/lib/utility/shared/math.lua b/lib/utility/shared/math.lua index 196e749..09e750b 100644 --- a/lib/utility/shared/math.lua +++ b/lib/utility/shared/math.lua @@ -1,4 +1,4 @@ -Math = {} +Math = Math or {} function Math.Clamp(value, min, max) return math.min(math.max(value, min), max) @@ -46,5 +46,44 @@ 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 + exports('Math', Math) + return Math \ No newline at end of file From 98633937752ea10d645a5cdb58f6432392df0d3f Mon Sep 17 00:00:00 2001 From: MrNewb <47620135+MrNewb@users.noreply.github.com> Date: Sun, 4 May 2025 14:51:56 -0400 Subject: [PATCH 03/15] small cleanup -- found by @retrizo --- modules/inventory/origen_inventory/server.lua | 1 - 1 file changed, 1 deletion(-) diff --git a/modules/inventory/origen_inventory/server.lua b/modules/inventory/origen_inventory/server.lua index 4bc27d4..f567fb9 100644 --- a/modules/inventory/origen_inventory/server.lua +++ b/modules/inventory/origen_inventory/server.lua @@ -55,7 +55,6 @@ Inventory.GetPlayerInventory = function(src) local playerItems = origen_inventory:GetInventory(src) local repackedTable = {} for _, v in pairs(playerItems.inventory) do - print(json.encode(v, { indent = true })) table.insert(repackedTable, { name = v.name, count = v.count, From 87b51e13e0511e61e7012272e012cb10b3f46a81 Mon Sep 17 00:00:00 2001 From: JericoFX Date: Sun, 4 May 2025 19:21:50 -0300 Subject: [PATCH 04/15] Update on cache and config --- lib/cache/client/cache.lua | 39 ++++++++++++++++--- lib/cache/shared/cache.lua | 79 ++++++++++++++++++++++++++++++-------- settings/clientConfig.lua | 21 +++++----- 3 files changed, 108 insertions(+), 31 deletions(-) diff --git a/lib/cache/client/cache.lua b/lib/cache/client/cache.lua index 7c6fd1d..df493c8 100644 --- a/lib/cache/client/cache.lua +++ b/lib/cache/client/cache.lua @@ -1,15 +1,31 @@ Cache = Require("lib/cache/shared/cache.lua") +local PlayerPedId = PlayerPedId +local GetVehiclePedIsIn = GetVehiclePedIsIn +local GetVehicleMaxNumberOfPassengers = GetVehicleMaxNumberOfPassengers +local GetPedInVehicleSeat = GetPedInVehicleSeat +local GetPlayerServerId = GetPlayerServerId +local GetSelectedPedWeapon = GetSelectedPedWeapon +local PlayerId = PlayerId + + -- Comparison functions for client-side state + +--- Get the player's ped ID +---@return integer local function GetPed() return PlayerPedId() end +--- Get the vehicle the player is in, if any +---@return integer | nil local function GetVehicle() local ped = Cache.Get("Ped") -- Use cached ped for efficiency - if not ped then return end -- Or handle error/default case + if not ped then return end -- Or handle error/default case return GetVehiclePedIsIn(ped, false) end +--- Get the seat of the player in the vehicle if the vehicle is occupied +---@return integer | nil local function GetVehicleSeat() local vehicle = Cache.Get("Vehicle") if not vehicle then return end @@ -22,15 +38,26 @@ local function GetVehicleSeat() end end +---Get The Server ID of the player +---@return integer | nil +local function GetServerId() + local ped = PlayerId() + if not ped then return end -- Return unarmed hash if no ped + return GetPlayerServerId(ped) +end + +--- Get the current weapon of the player +--- @return integer | nil local function GetWeapon() local ped = Cache.Get("Ped") if not ped then return end -- Return unarmed hash if no ped return GetSelectedPedWeapon(ped) end -Cache.Create("Ped", GetPed, 1000) -- Check ped every second (adjust as needed) -Cache.Create("Vehicle", GetVehicle, 500) -- Check vehicle every 500ms -Cache.Create("Seat", GetVehicleSeat, 500) -- Check if in vehicle every 500ms -Cache.Create("Weapon", GetWeapon, 250) -- Check weapon every 250ms +Cache.Create("Ped", GetPed, 1000) -- Check ped every second (adjust as needed) +Cache.Create("Vehicle", GetVehicle, 500) -- Check vehicle every 500ms +Cache.Create("Seat", GetVehicleSeat, 500) -- Check if in vehicle every 500ms +Cache.Create("Weapon", GetWeapon, 250) -- Check weapon every 250ms +Cache.Create("ServerId", GetServerId, 1000) -- Check server ID every second -return Cache \ No newline at end of file +return Cache diff --git a/lib/cache/shared/cache.lua b/lib/cache/shared/cache.lua index 30e568f..f80526a 100644 --- a/lib/cache/shared/cache.lua +++ b/lib/cache/shared/cache.lua @@ -1,8 +1,20 @@ local Cache = {} +local Config = require("lib/settings/clientConfig.lua") +local max = 5000 +local CreateThread = CreateThread +local Wait = Wait +local GetGameTimer = GetGameTimer + + Cache.Caches = Cache.Caches or {} Cache.LoopRunning = Cache.LoopRunning or false -local max = 5000 +local function print(...) + if Config.Debug then + print("^2[Cache]^0", ...) + end +end + local function StartLoop() if Cache.LoopRunning then return end Cache.LoopRunning = true @@ -44,30 +56,65 @@ local function StartLoop() end function Cache.Create(name, compare, waitTime) - Cache.Caches[name] = Cache.Caches[name] or {} - Cache.Caches[name].WaitTime = waitTime or max - Cache.Caches[name].Compare = compare - Cache.Caches[name].OnChange = Cache.Caches[name].OnChange or {} - Cache.Caches[name].Value = compare() - print("Cache created: " .. name .. " with initial value: " .. tostring(Cache.Caches[name].Value)) - for _, onChange in pairs(Cache.Caches[name].OnChange) do - onChange(Cache.Caches[name].Value, nil) + assert(name, "Cache name is required.") + assert(compare, "Comparison function is required.") + assert(type(compare) == "function", "Comparison function must be a function.") + local _name = tostring(name) -- Ensure name is a string + local cache = Cache.Caches[_name] + if cache and cache.Compare == compare then + print(name .. " already exists with the same comparison function.") + return cache end - print("Cache created: " .. name .. " with initial value: " .. tostring(Cache.Caches[name].Value)) + cache = nil -- clean variable, so we can use the same name for the new cache + local s, r = pcall(function() -- Try to create the cache and catch any errors + local _cache = { + Name = _name, + Compare = compare, + WaitTime = waitTime or max, + LastChecked = nil, + OnChange = {}, + Value = compare() + } + Cache.Caches[_name] = _cache + print(_name .. " created with initial value: " .. tostring(Cache.Caches[_name].Value)) + for _, onChange in pairs(_cache.OnChange) do + onChange(_cache.Value, nil) + end + end) + if not s then + print("Error creating cache '" .. _name .. "': " .. tostring(r)) + return nil + end + return StartLoop() end function Cache.Get(name) - local cache = Cache.Caches[name] + assert(name, "Cache name is required.") + local _name = tostring(name) + local cache = Cache.Caches[_name] return cache and cache.Value or nil end function Cache.OnChange(name, onChange) - local cache = Cache.Caches[name] - assert(cache, "Cache with name '" .. name .. "' does not exist.") - table.insert(cache.OnChange, onChange) + assert(name, "Cache name is required.") + local _name = tostring(name) -- Ensure name is a string + local cache = Cache.Caches[_name] + assert(cache, "Cache with name '" .. _name .. "' does not exist.") + cache.OnChange[#cache.OnChange + 1] = onChange +end + +function Cache.Remove(name) + assert(name, "Cache name is required.") + local _name = tostring(name) -- Ensure name is a string + local cache = Cache.Caches[_name] + if cache then + Cache.Caches[_name] = nil + print(_name .. " removed from cache.") + if next(Cache.Caches) == nil then + Cache.LoopRunning = false -- Stop the loop if no caches are left + end + end end return Cache - - diff --git a/settings/clientConfig.lua b/settings/clientConfig.lua index 9fb6add..6da8aee 100644 --- a/settings/clientConfig.lua +++ b/settings/clientConfig.lua @@ -1,9 +1,12 @@ -BridgeClientConfig = {} -BridgeClientConfig.InputSystem = "auto" -- [ auto | ox_lib | qb-input ] -BridgeClientConfig.MenuSystem = "auto" -- [ auto | ox_lib | qb-menu ] -BridgeClientConfig.ProgressBarSystem = "auto" -- [ auto | ox_lib | progressbar ] -BridgeClientConfig.VehicleKey = "auto" -- [ auto | qb-vehiclekeys | MrNewbVehicleKeys | jaksams_VehiclesKeys | wasabi_carlock | mk_vehiclekeys | qbx_vehiclekeys | qs-vehiclekeys | t1ger_keys | Renewed-Vehiclekeys | mono_carkeys| cd_garage | okokGarage | F_RealCarKeysSystem -BridgeClientConfig.Fuel = "auto" -- [ auto | LegacyFuel | ox_fuel | ps-fuel | qs-fuelstations | Renewed-Fuel | ti_fuel | lc_fuel | x-fuel | cdn-fuel | esx-sna-fuel | BigDaddy-Fuel | okokGasStation ] -BridgeClientConfig.TargetSystem = "auto" -- [ auto | ox_target | qb-target | sleepless_interact ] -- sleepless is only partially supported and would need another system in place - -return BridgeClientConfig \ No newline at end of file +BridgeClientConfig = {} +BridgeClientConfig.InputSystem = "auto" -- [ auto | ox_lib | qb-input ] +BridgeClientConfig.MenuSystem = "auto" -- [ auto | ox_lib | qb-menu ] +BridgeClientConfig.ProgressBarSystem = "auto" -- [ auto | ox_lib | progressbar ] +BridgeClientConfig.VehicleKey = +"auto" -- [ auto | qb-vehiclekeys | MrNewbVehicleKeys | jaksams_VehiclesKeys | wasabi_carlock | mk_vehiclekeys | qbx_vehiclekeys | qs-vehiclekeys | t1ger_keys | Renewed-Vehiclekeys | mono_carkeys| cd_garage | okokGarage | F_RealCarKeysSystem +BridgeClientConfig.Fuel = +"auto" -- [ auto | LegacyFuel | ox_fuel | ps-fuel | qs-fuelstations | Renewed-Fuel | ti_fuel | lc_fuel | x-fuel | cdn-fuel | esx-sna-fuel | BigDaddy-Fuel | okokGasStation ] +BridgeClientConfig.TargetSystem = +"auto" -- [ auto | ox_target | qb-target | sleepless_interact ] -- sleepless is only partially supported and would need another system in place +BridgeClientConfig.Debug = false +return BridgeClientConfig From fc3d1b162a08464ec8333100b0b12ac272161e20 Mon Sep 17 00:00:00 2001 From: JericoFX Date: Mon, 5 May 2025 11:22:38 -0300 Subject: [PATCH 05/15] Marker --- fxmanifest.lua | 1 + lib/markers/client/markers.lua | 108 ++++++++++++++++++++++++++++++--- lib/markers/server/server.lua | 24 ++++++++ lib/sql/server/sqlHandler.lua | 6 +- 4 files changed, 127 insertions(+), 12 deletions(-) create mode 100644 lib/markers/server/server.lua diff --git a/fxmanifest.lua b/fxmanifest.lua index f968048..48cfc4f 100644 --- a/fxmanifest.lua +++ b/fxmanifest.lua @@ -31,6 +31,7 @@ server_scripts { 'modules/notify/**/server.lua', 'modules/housing/**/server.lua', 'modules/skills/**/server.lua', + "lib/**/server.lua", 'init.lua', } diff --git a/lib/markers/client/markers.lua b/lib/markers/client/markers.lua index f587da3..c83dc60 100644 --- a/lib/markers/client/markers.lua +++ b/lib/markers/client/markers.lua @@ -1,6 +1,39 @@ -Marker = {} +Marker = { +} +local Created = setmetatable({}, { __mode = "k" }) +local id = Require("lib/utility/shared/ids") + +--- 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 + +AddEventHandler("community_bridge:client:marker", function(data) + if not validateMarkerData(data) then return end + if source == "" then return end + Marker.DrawMarker(data) +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 number function Marker.DrawMarker(data) + local _id = data.id or id.Random() local position = data.position or vector3(0.0, 0.0, 0.0) local offset = data.offset or vector3(0.0, 0.0, 0.0) local marker = data.marker or 1 @@ -10,17 +43,72 @@ function Marker.DrawMarker(data) local color = data.color or vector3(0, 255, 0) local alpha = data.alpha or 255 local bobUpAndDown = data.bobUpAndDown - DrawMarker( - marker, - pos.x, pos.y, pos.z, - 0.0, 0.0, 0.0, - rotation.x, rotation.y, rotation.z, - size.x, size.y, size.z, - color.r, color.g, color.b, alpha, - bobUpAndDown, false, false - ) + local interaction = data.interaction or false + Created[_id] = { + position = pos, + rotation = rotation, + size = size, + color = color, + alpha = alpha, + bobUpAndDown = + bobUpAndDown, + marker = marker, + offset = offset, + interaction = interaction, + id = _id, + } + return _id end +function Marker.RemoveMarker(id) + if Created[id] then + Created[id] = nil + return true + end + return false +end + +function Marker.Draw() + while true do + Wait(0) + if not next(Created) then + Wait(1000) -- Reduce CPU usage when no markers are present + goto continue + end + + for id, _ in pairs(Created) do + if Created[id] then + local data = Created[id] + if #(data.position - GetEntityCoords(PlayerPedId())) > 100.0 then + goto continue + else + DrawMarker( + data.marker, + data.position.x, data.position.y, data.position.z, + 0.0, 0.0, 0.0, + data.rotation.x, data.rotation.y, data.rotation.z, + data.size.x, data.size.y, data.size.z, + data.color.x, data.color.y, data.color.z, data.alpha, + data.bobUpAndDown, false, false + ) + if data.interaction then + local playerCoords = GetEntityCoords(PlayerPedId()) + local distance = #(data.position - playerCoords) + if distance < 2.0 then + if IsControlJustReleased(0, 38) then -- E key + data.interaction(data.id) + end + end + end + end + end + end + ::continue:: + end +end + +Marker.Draw() -- Start the marker drawing loop exports("Marker", Marker) + return Marker diff --git a/lib/markers/server/server.lua b/lib/markers/server/server.lua new file mode 100644 index 0000000..c009c7d --- /dev/null +++ b/lib/markers/server/server.lua @@ -0,0 +1,24 @@ +local function RegisterNewMarker(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 + 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 + 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 + end + + if not data.size or not data.size.x or not data.size.y or not data.size.z then + print("Invalid marker size. Must be a vector3 with x, y, and z dimensions.") + return + end + + TriggerClientEvent("community_bridge:client:marker", source, data) +end + +RegisterNetEvent("community_bridge:server:createMarker", RegisterNewMarker) +exports("RegisterNewMarker", RegisterNewMarker) diff --git a/lib/sql/server/sqlHandler.lua b/lib/sql/server/sqlHandler.lua index 942bcf2..9336438 100644 --- a/lib/sql/server/sqlHandler.lua +++ b/lib/sql/server/sqlHandler.lua @@ -2,6 +2,8 @@ SQL = {} Require("lib/MySQL.lua", "oxmysql") + + function SQL.Create(tableName, columns) assert(MySQL, "Tried using module SQL without MySQL being loaded") local columnsList = {} @@ -26,7 +28,7 @@ function SQL.InsertOrUpdate(tableName, data) for column, value in pairs(data) do table.insert(columns, column) - table.insert(values, "'" .. value .. "'") -- Ensure values are properly quoted + table.insert(values, "'" .. value .. "'") -- Ensure values are properly quoted table.insert(updates, column .. " = VALUES(" .. column .. ")") -- Use VALUES() for update end @@ -65,4 +67,4 @@ exports('SQL', function() return SQL end) -return SQL \ No newline at end of file +return SQL From 70593cc9f5608ea445a34b21685240cb33b2d357 Mon Sep 17 00:00:00 2001 From: JericoFX Date: Mon, 5 May 2025 11:27:50 -0300 Subject: [PATCH 06/15] update markers From 3e6bc0dd818daae985d7143ef07686801b15c00b Mon Sep 17 00:00:00 2001 From: MrNewb <47620135+MrNewb@users.noreply.github.com> Date: Mon, 5 May 2025 10:45:00 -0400 Subject: [PATCH 07/15] account type for qb format to esx --- modules/framework/es_extended/server.lua | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/modules/framework/es_extended/server.lua b/modules/framework/es_extended/server.lua index 365a3f2..31fc9a8 100644 --- a/modules/framework/es_extended/server.lua +++ b/modules/framework/es_extended/server.lua @@ -243,6 +243,7 @@ end Framework.AddAccountBalance = function(src, _type, amount) local xPlayer = ESX.GetPlayerFromId(src) if not xPlayer then return end + if _type == 'cash' then _type = 'money' end return xPlayer.addAccountMoney(_type, amount) end @@ -251,6 +252,7 @@ end Framework.RemoveAccountBalance = function(src, _type, amount) local xPlayer = ESX.GetPlayerFromId(src) if not xPlayer then return end + if _type == 'cash' then _type = 'money' end xPlayer.removeAccountMoney(_type, amount) return true end @@ -260,6 +262,7 @@ end Framework.GetAccountBalance = function(src, _type) local xPlayer = ESX.GetPlayerFromId(src) if not xPlayer then return end + if _type == 'cash' then _type = 'money' end return xPlayer.getAccount(_type).money end @@ -330,6 +333,4 @@ Framework.Commands.Add = function(name, help, arguments, argsrequired, callback, help = help, arguments = arguments }) -end - --- test \ No newline at end of file +end \ No newline at end of file From 70199ea3106785d2a54b2cee19b866040572bcf0 Mon Sep 17 00:00:00 2001 From: Luxu <122475744+luxu-gg@users.noreply.github.com> Date: Mon, 5 May 2025 18:11:58 +0100 Subject: [PATCH 08/15] okokPhone integration --- modules/phone/okokPhone/client.lua | 16 +++++++++ modules/phone/okokPhone/server.lua | 55 ++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 modules/phone/okokPhone/client.lua create mode 100644 modules/phone/okokPhone/server.lua diff --git a/modules/phone/okokPhone/client.lua b/modules/phone/okokPhone/client.lua new file mode 100644 index 0000000..623b01a --- /dev/null +++ b/modules/phone/okokPhone/client.lua @@ -0,0 +1,16 @@ +local resourceName = "okokPhone" +local configValue = BridgeSharedConfig.Phone +if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end + +Phone = Phone or {} + +---comment +---@param email string +---@param title string +---@param message string +---@return boolean +---@diagnostic disable-next-line: duplicate-set-field +Phone.SendEmail = function(email, title, message) + local success = lib.callback.await('community_bridge:Callback:okokPhone:sendEmail', false, email, title, message) --[[ @as boolean ]] + return success +end diff --git a/modules/phone/okokPhone/server.lua b/modules/phone/okokPhone/server.lua new file mode 100644 index 0000000..67643cb --- /dev/null +++ b/modules/phone/okokPhone/server.lua @@ -0,0 +1,55 @@ +---@class NewEmail +---@field sender string +---@field recipients string[] +---@field subject string +---@field actions? EmailAction[] +---@field body string + +---@class EmailAction +---@field id string +---@field label string +---@field event string? +---@field exports string? +---@field server boolean +---@field data any + +local resourceName = "okokPhone" +local configValue = BridgeSharedConfig.Phone +if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end +Phone = Phone or {} + +---comment +---@param src number +---@return number| boolean +---@diagnostic disable-next-line: duplicate-set-field +Phone.GetPlayerPhone = function(src) + return exports.okokPhone:getPhoneNumberFromSource(src) or false +end + +---comment +---@param src number +---@param email string +---@param title string +---@param message string +---@return boolean +---@diagnostic disable-next-line: duplicate-set-field +Phone.SendEmail = function(src, email, title, message) + local senderAddress = exports.okokPhone:getEmailAddressFromSource(src) --[[ @as string? ]] + if not senderAddress then return false end + + ---@type NewEmail + local data = { + sender = senderAddress, + recipients = { email }, + subject = title, + body = message, + } + + local success = exports.okokPhone:sendEmail(data) --[[ @as boolean ]] + return success +end + + +lib.callback.registry('community_bridge:Callback:okokPhone:sendEmail', function(src, email, title, message) + return Phone.SendEmail(src, email, title, message) +end) From a015e681b3b6ec98863747be83ec9bd2431d9091 Mon Sep 17 00:00:00 2001 From: JericoFX Date: Mon, 5 May 2025 15:04:11 -0300 Subject: [PATCH 09/15] simple refractor with local functions --- .vscode/settings.json | 3 + lib/utility/client/utility.lua | 343 ++++++++++++++++++--------------- 2 files changed, 194 insertions(+), 152 deletions(-) create mode 100644 .vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..febb024 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "githubPullRequests.ignoredPullRequestBranches": ["main"] +} diff --git a/lib/utility/client/utility.lua b/lib/utility/client/utility.lua index 5363e30..d9a87bd 100644 --- a/lib/utility/client/utility.lua +++ b/lib/utility/client/utility.lua @@ -1,80 +1,163 @@ +---@class Utility Utility = Utility or {} local blipIDs = {} local spawnedPeds = {} ----commentThis will create a prop with the passed model string at the coords and heading specified optionally networked or not. ----@param model string | number ----@param coords table +-- === Local Helpers === + +---Get the hash of a model (string or number) +---@param model string|number +---@return number +local function getModelHash(model) + if type(model) ~= 'number' then + return joaat(model) + end + return model +end + +---Ensure a model is loaded into memory +---@param model string|number +---@return boolean, number +local function ensureModelLoaded(model) + local hash = getModelHash(model) + if not IsModelValid(hash) and not IsModelInCdimage(hash) then return false, hash end + RequestModel(hash) + local count = 0 + while not HasModelLoaded(hash) and count < 30000 do + Wait(0) + count = count + 1 + end + return HasModelLoaded(hash), hash +end + +---Add a text entry if possible +---@param key string +---@param text string +local function addTextEntryOnce(key, text) + if not AddTextEntry then return end + AddTextEntry(key, text) +end + +---Create a blip safely and store its reference +---@param coords vector3 +---@param sprite number +---@param color number +---@param scale number +---@param label string +---@param shortRange boolean +---@param displayType number +---@return number +local function safeAddBlip(coords, sprite, color, scale, label, shortRange, displayType) + local blip = AddBlipForCoord(coords.x, coords.y, coords.z) + SetBlipSprite(blip, sprite or 8) + SetBlipColour(blip, color or 3) + SetBlipScale(blip, scale or 0.8) + SetBlipDisplay(blip, displayType or 2) + SetBlipAsShortRange(blip, shortRange) + addTextEntryOnce(label, label) + BeginTextCommandSetBlipName(label) + EndTextCommandSetBlipName(blip) + table.insert(blipIDs, blip) + return blip +end + +---Remove a blip safely from the stored list +---@param blip number +---@return boolean +local function safeRemoveBlip(blip) + for i, storedBlip in ipairs(blipIDs) do + if storedBlip == blip then + RemoveBlip(storedBlip) + table.remove(blipIDs, i) + return true + end + end + return false +end + +---Add a text entry if possible (shortcut) +---@param text string +local function safeAddTextEntry(text) + if not AddTextEntry then return end + AddTextEntry(text, text) +end + +-- === Public Utility Functions === + +---Create a prop with the given model and coordinates +---@param model string|number +---@param coords vector3 ---@param heading number ---@param networked boolean ----@return number | nil -Utility.CreateProp = function(model, coords, heading, networked) - Utility.LoadModel(model) - if not HasModelLoaded(model) then return nil, Prints.Error("Model Has Not Loaded") end - local propEntity = CreateObject(model, coords.x, coords.y, coords.z, networked, false, false) +---@return number|nil +function Utility.CreateProp(model, coords, heading, networked) + local loaded, hash = ensureModelLoaded(model) + if not loaded then return nil, Prints and Prints.Error and Prints.Error("Model Has Not Loaded") end + local propEntity = CreateObject(hash, coords.x, coords.y, coords.z, networked, false, false) SetEntityHeading(propEntity, heading) - SetModelAsNoLongerNeeded(model) + SetModelAsNoLongerNeeded(hash) return propEntity end ----This will get the street name and crossing name at the specified coordinates. ----@param coords table ----@return string ----@return string -Utility.GetStreetNameAtCoords = function(coords) +---Get street and crossing names at given coordinates +---@param coords vector3 +---@return string, string +function Utility.GetStreetNameAtCoords(coords) local streetHash, crossingHash = GetStreetNameAtCoord(coords.x, coords.y, coords.z) - local streetName = GetStreetNameFromHashKey(streetHash) - local crossingName = GetStreetNameFromHashKey(crossingHash) - return streetName, crossingName + return GetStreetNameFromHashKey(streetHash), GetStreetNameFromHashKey(crossingHash) end ----This will create a vehicle with the passed model string at the coords and heading specified. ----@param model string ----@param coords table +---Create a vehicle with the given model and coordinates +---@param model string|number +---@param coords vector3 ---@param heading number ---@param networked boolean ----@return number| nil ----@return table -Utility.CreateVehicle = function(model, coords, heading, networked) - Utility.LoadModel(model) - if not HasModelLoaded(model) then return nil, {}, Prints.Error("Model Has Not Loaded") end - local vehicle = CreateVehicle(model, coords.x, coords.y, coords.z, heading, networked, false) +---@return number|nil, table +function Utility.CreateVehicle(model, coords, heading, networked) + local loaded, hash = ensureModelLoaded(model) + if not loaded then return nil, {}, Prints and Prints.Error and Prints.Error("Model Has Not Loaded") end + local vehicle = CreateVehicle(hash, coords.x, coords.y, coords.z, heading, networked, false) SetVehicleHasBeenOwnedByPlayer(vehicle, true) SetVehicleNeedsToBeHotwired(vehicle, false) SetVehRadioStation(vehicle, "OFF") - SetModelAsNoLongerNeeded(model) - return vehicle, { networkid = NetworkGetNetworkIdFromEntity(vehicle) or 0, coords = GetEntityCoords(vehicle), heading = GetEntityHeading(vehicle), } + SetModelAsNoLongerNeeded(hash) + return vehicle, { + networkid = NetworkGetNetworkIdFromEntity(vehicle) or 0, + coords = GetEntityCoords(vehicle), + heading = GetEntityHeading(vehicle), + } end ----This will create a ped with the passed model string at the coords and heading specified. ----@param model string ----@param coords table +---Create a ped with the given model and coordinates +---@param model string|number +---@param coords vector3 ---@param heading number ---@param networked boolean ----@return number| nil -Utility.CreatePed = function(model, coords, heading, networked, settings) - Utility.LoadModel(model) - if not HasModelLoaded(model) then return nil, Prints.Error("Model Has Not Loaded") end - local spawnedEntity = CreatePed(0, model, coords.x, coords.y, coords.z, heading, networked, false) - SetModelAsNoLongerNeeded(model) +---@param settings table|nil +---@return number|nil +function Utility.CreatePed(model, coords, heading, networked, settings) + local loaded, hash = ensureModelLoaded(model) + if not loaded then return nil, Prints and Prints.Error and Prints.Error("Model Has Not Loaded") end + local spawnedEntity = CreatePed(0, hash, coords.x, coords.y, coords.z, heading, networked, false) + SetModelAsNoLongerNeeded(hash) table.insert(spawnedPeds, spawnedEntity) return spawnedEntity end ----This will display a busy spinner with the passed text. +---Show a busy spinner with the given text ---@param text string ---@return boolean -Utility.StartBusySpinner = function(text) - AddTextEntry(text, text) +function Utility.StartBusySpinner(text) + safeAddTextEntry(text) BeginTextCommandBusyString(text) AddTextComponentSubstringPlayerName(text) EndTextCommandBusyString(0) return true end ----This will stop a busy spinner if one is currently active. +---Stop the busy spinner if active ---@return boolean -Utility.StopBusySpinner = function() +function Utility.StopBusySpinner() if BusyspinnerIsOn() then BusyspinnerOff() return true @@ -82,64 +165,38 @@ Utility.StopBusySpinner = function() return false end ----comment Creates a blip at the specified coordinates with the specified parameters. If sprite/color/scale/label are not provided, default values will be used. ----@param coords table +---Create a blip at the given coordinates +---@param coords vector3 ---@param sprite number ---@param color number ---@param scale number ---@param label string ---@param shortRange boolean ---@param displayType number ----@return integer -Utility.CreateBlip = function(coords, sprite, color, scale, label, shortRange, displayType) - local blip = AddBlipForCoord(coords.x, coords.y, coords.z) - SetBlipSprite(blip, sprite or 8) - SetBlipColour(blip, color or 3) - SetBlipScale(blip, scale or 0.8) - SetBlipDisplay(blip, displayType or 2) - SetBlipAsShortRange(blip, shortRange) - AddTextEntry(label, label) - BeginTextCommandSetBlipName(label) - EndTextCommandSetBlipName(blip) - table.insert(blipIDs, blip) - return blip +---@return number +function Utility.CreateBlip(coords, sprite, color, scale, label, shortRange, displayType) + return safeAddBlip(coords, sprite, color, scale, label, shortRange, displayType) end ----This will remove a blip if it exists in the blipIDs table. +---Remove a blip if it exists ---@param blip number ---@return boolean -Utility.RemoveBlip = function(blip) - local success = false - for i, storedBlip in ipairs(blipIDs) do - if storedBlip == blip then - RemoveBlip(storedBlip) - table.remove(blipIDs, i) - success = true - break - end - end - return success +function Utility.RemoveBlip(blip) + return safeRemoveBlip(blip) end ----Loads a model into memory. If the model is not valid or not in the game files, it will return false. ----@param model string | number +---Load a model into memory +---@param model string|number ---@return boolean -Utility.LoadModel = function(model) - if type(model) ~= 'number' then model = joaat(model) end -- Use GetHashKey instead of joaat for client - if not IsModelValid(model) and not IsModelInCdimage(model) then return false end - RequestModel(model) - local count = 0 - while not HasModelLoaded(model) and count < 30000 do - Wait(0) - count = count + 1 - end - return HasModelLoaded(model) +function Utility.LoadModel(model) + local loaded = ensureModelLoaded(model) + return loaded end ----This function will request an animation dictionary and wait until it is loaded. If the dictionary is not valid, it will return false. +---Request an animation dictionary ---@param dict string ---@return boolean -Utility.RequestAnimDict = function(dict) +function Utility.RequestAnimDict(dict) RequestAnimDict(dict) local count = 0 while not HasAnimDictLoaded(dict) and count < 30000 do @@ -149,10 +206,10 @@ Utility.RequestAnimDict = function(dict) return HasAnimDictLoaded(dict) end ----This will remove a ped if it exists in the spawnedPeds table. It will also delete the entity if it exists. +---Remove a ped if it exists ---@param entity number ---@return boolean -Utility.RemovePed = function(entity) +function Utility.RemovePed(entity) local success = false if DoesEntityExist(entity) then DeleteEntity(entity) @@ -167,45 +224,44 @@ Utility.RemovePed = function(entity) return success end ----This will use a native text input menu to allow the user to enter text. It will return the entered text or false if cancelled. +---Show a native input menu and return the result ---@param text string ---@param length number ----@return string -Utility.NativeInputMenu = function(text, length) - local maxLength = Math.Clamp(length, 1, 50) - local menutText = text or 'enter text' - AddTextEntry(menutText, menutText) - DisplayOnscreenKeyboard(1, menutText, "", "", "", "", "", maxLength) - while(UpdateOnscreenKeyboard() == 0) do +---@return string|boolean +function Utility.NativeInputMenu(text, length) + local maxLength = Math and Math.Clamp and Math.Clamp(length, 1, 50) or math.min(math.max(length or 10, 1), 50) + local menuText = text or 'enter text' + safeAddTextEntry(menuText) + DisplayOnscreenKeyboard(1, menuText, "", "", "", "", "", maxLength) + while (UpdateOnscreenKeyboard() == 0) do DisableAllControlActions(0) Wait(0) end - if(GetOnscreenKeyboardResult()) then - local result = GetOnscreenKeyboardResult() - return result + if (GetOnscreenKeyboardResult()) then + return GetOnscreenKeyboardResult() end return false end ----This will get the current skin data of the entity passed. It will return a table with the clothing and props data. +---Get the skin data of a ped ---@param entity number ---@return table -Utility.GetEntitySkinData = function(entity) - local skinData = {} +function Utility.GetEntitySkinData(entity) + local skinData = { clothing = {}, props = {} } for i = 0, 11 do - skinData.clothing[i] = {GetPedDrawableVariation(entity, i), GetPedTextureVariation(entity, i)} + skinData.clothing[i] = { GetPedDrawableVariation(entity, i), GetPedTextureVariation(entity, i) } end for i = 0, 13 do - skinData.props[i] = {GetPedPropIndex(entity, i), GetPedPropTextureIndex(entity, i)} + skinData.props[i] = { GetPedPropIndex(entity, i), GetPedPropTextureIndex(entity, i) } end return skinData end ----This will set the skin data of the entity passed. It will set the clothing and props data from the skinData table. +---Apply skin data to a ped ---@param entity number ---@param skinData table ---@return boolean -Utility.SetEntitySkinData = function(entity, skinData) +function Utility.SetEntitySkinData(entity, skinData) for i = 0, 11 do SetPedComponentVariation(entity, i, skinData.clothing[i][1], skinData.clothing[i][2], 0) end @@ -215,9 +271,9 @@ Utility.SetEntitySkinData = function(entity, skinData) return true end ----This will reload the skin data of the entity passed. It will set the clothing and props data from the skinData table and delete any attached objects. +---Reload the player's skin and remove attached objects ---@return boolean -Utility.ReloadSkin = function() +function Utility.ReloadSkin() local skinData = Utility.GetEntitySkinData(cache.ped) Utility.SetEntitySkinData(cache.ped, skinData) for _, props in pairs(GetGamePool("CObject")) do @@ -230,20 +286,20 @@ Utility.ReloadSkin = function() return true end ----This will display a native help text on the screen. It will add a text entry and display it for the specified duration. +---Show a native help text ---@param text string ---@param duration number -Utility.HelpText = function(text, duration) - AddTextEntry(text, text) +function Utility.HelpText(text, duration) + safeAddTextEntry(text) BeginTextCommandDisplayHelp(text) EndTextCommandDisplayHelp(0, false, true, duration or 5000) end ----This will display 3D help text at the specified coordinates. ----@param coords table +---Draw 3D help text in the world +---@param coords vector3 ---@param text string ---@param scale number -Utility.Draw3DHelpText = function(coords, text, scale) +function Utility.Draw3DHelpText(coords, text, scale) local onScreen, x, y = GetScreenCoordFromWorldCoord(coords.x, coords.y, coords.z) if onScreen then SetTextScale(scale or 0.35, scale or 0.35) @@ -259,19 +315,19 @@ Utility.Draw3DHelpText = function(coords, text, scale) end end ----This will display a native help text on the screen. It will add a text entry and display it for the specified duration. +---Show a native notification ---@param text string -Utility.NotifyText = function(text) - AddTextEntry(text, text) +function Utility.NotifyText(text) + safeAddTextEntry(text) SetNotificationTextEntry(text) DrawNotification(false, true) end ----This will teleport a player to the specified coordinates. If a condition function is passed it will verify that condition is met and then it will fade the screen out and in, freeze the player during the teleport to allow for collisions to load, and call the afterTeleportFunction if provided. ----@param coords table ----@param conditionFunction function | optional ----@param afterTeleportFunction function | optional -Utility.TeleportPlayer = function(coords, conditionFunction, afterTeleportFunction) +---Teleport the player to given coordinates +---@param coords vector3 +---@param conditionFunction function|nil +---@param afterTeleportFunction function|nil +function Utility.TeleportPlayer(coords, conditionFunction, afterTeleportFunction) if conditionFunction ~= nil then if not conditionFunction() then return @@ -297,22 +353,19 @@ Utility.TeleportPlayer = function(coords, conditionFunction, afterTeleportFuncti end end ----This will get a model hash from a string or number. ----@param model string | number +---Get the hash from a model +---@param model string|number ---@return number -Utility.GetEntityHashFromModel = function(model) - if type(model) ~= 'number' then model = joaat(model) end -- Use GetHashKey instead of joaat for client - return model +function Utility.GetEntityHashFromModel(model) + return getModelHash(model) end ----commentThis will get the closest player, the distance to that player from the coords and the server ID of that player. ----@param coords table ----@param distanceScope number ----@param includeMe boolean ----@return integer ----@return integer ----@return integer -Utility.GetClosestPlayer = function(coords, distanceScope, includeMe) +---Get the closest player to given coordinates +---@param coords vector3|nil +---@param distanceScope number|nil +---@param includeMe boolean|nil +---@return number, number, number +function Utility.GetClosestPlayer(coords, distanceScope, includeMe) local players = GetActivePlayers() local closestPlayer = 0 local selfPed = cache.ped @@ -334,33 +387,20 @@ Utility.GetClosestPlayer = function(coords, distanceScope, includeMe) return closestPlayer, closestDistance, GetPlayerServerId(closestPlayer) end ----This function is is deprecated and will be removed in the future. Please use Pont.Register instead. ----@param pointID string ----@param pointCoords table ----@param pointDistance number ----@param _onEnter function ----@param _onExit function ----@param _nearby function -Utility.RegisterPoint = function(pointID, pointCoords, pointDistance, _onEnter, _onExit, _nearby) +-- Deprecated point functions (no changes) +function Utility.RegisterPoint(pointID, pointCoords, pointDistance, _onEnter, _onExit, _nearby) return Point.Register(pointID, pointCoords, pointDistance, nil, _onEnter, _onExit, _nearby) end ----This function is is deprecated and will be removed in the future. Please use Point.Get instead. ----@param pointID string -Utility.GetPointById = function(pointID) +function Utility.GetPointById(pointID) return Point.Get(pointID) end ----This function is is deprecated and will be removed in the future. Please use Point.GetAll instead. ----@return table | nil -Utility.GetActivePoints = function() +function Utility.GetActivePoints() return Point.GetAll() end ----This function is is deprecated and will be removed in the future. Please use Point.Remove instead. ----@param pointID string ----@return nil -Utility.RemovePoint = function(pointID) +function Utility.RemovePoint(pointID) return Point.Remove(pointID) end @@ -379,5 +419,4 @@ AddEventHandler('onResourceStop', function(resource) end) exports('Utility', Utility) - -return Utility \ No newline at end of file +return Utility From aa1e621f905628e187a4d39407e7f08cd65d82fb Mon Sep 17 00:00:00 2001 From: JericoFX Date: Mon, 5 May 2025 15:49:03 -0300 Subject: [PATCH 10/15] refractor callbacks --- lib/utility/shared/callbacks.lua | 314 +++++++++++++------------------ 1 file changed, 127 insertions(+), 187 deletions(-) diff --git a/lib/utility/shared/callbacks.lua b/lib/utility/shared/callbacks.lua index f0b7965..97cab1e 100644 --- a/lib/utility/shared/callbacks.lua +++ b/lib/utility/shared/callbacks.lua @@ -1,197 +1,137 @@ -Callbacks = {} -cbData = {} -Callback = Callback or {} +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' +} -local resource = GetCurrentResourceName() or 'unknown' +-- Utility functions +local function generateCallbackId(name) + return string.format('%s_%d', name, math.random(1000000, 9999999)) +end -local clientToServerName = resource .. ':server:CS:TriggerCallback' -local clientToServerBackToClientName = resource .. ':client:CSC:TriggerCallback' +local function handleResponse(registry, name, callbackId, ...) + local data = registry[callbackId] + if not data then return end -local serverToClientName = resource .. ':client:SC:TriggerCallback' -local serverToClientBackToServerName = resource .. ':server:SCS:TriggerCallback' + 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) + return #result == 1 and result[1] or table.unpack(result) + 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, ...) + local handler = Callback[name] + if not handler then return end + + local result = table.pack(handler(source, ...)) + TriggerClientEvent(EVENT_NAMES.CLIENT_RESPONSE, source, 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 #result == 1 and result[1] or 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) - -if not IsDuplicityVersion() then goto client end - --- -- -- -- -- -- -- -- -- -- --- ▄▀▀ ██▀ █▀▄ █ █ ██▀ █▀▄ --- ▄█▀ █▄▄ █▀▄ ▀▄▀ █▄▄ █▀▄ --- -- -- -- -- -- -- -- -- -- - --- client to server rebound -function Callback.Register(name, callback, all) - Callback[name] = { - callback = callback, - toAll = all - } -end - --- Handle client requests and send response back to client(s) -RegisterNetEvent(clientToServerName, function(name, cbId, ...) - local src = source - local data = Callback[name] - if not data then return end - local func = data.callback - if not func then return end - local toAll = data.toAll and -1 or src - - -- Create response handler - local packed = table.pack(func(src, ...)) - TriggerClientEvent(clientToServerBackToClientName, toAll, name, cbId, table.unpack(packed)) -end) - --- Server to client trigger function - supports both callback and direct return -function Callback.Trigger(name, src, callbackOrArg, ...) - if src == nil then src = -1 end - - -- Determine if the third parameter is a callback function or an argument - local hasCallback = type(callbackOrArg) == 'function' or (type(callbackOrArg) == 'table' and rawget(callbackOrArg, '__cfx_functionReference')) - local callback = hasCallback and callbackOrArg or nil - -- Adjust args based on whether the callback is present - local args = hasCallback and {...} or {callbackOrArg, ...} - - local cbId = name .. '_' .. math.random(1000000, 9999999) - local p = promise.new() - - -- Store promise data - cbData[cbId] = { - cb = callback, - p = p - } - - -- Trigger for single player or multiple players - if type(src) == 'table' then - for i, d in pairs(src) do - TriggerClientEvent(serverToClientName, tonumber(d), name, cbId, table.unpack(args)) - end - else - TriggerClientEvent(serverToClientName, tonumber(src), name, cbId, table.unpack(args)) - end - - -- If no callback was provided, wait for the promise and return directly - - local result = Citizen.Await(p) - -- If there's only one value, return it directly - if #result == 1 then - return result[1] - else - return table.unpack(result or {}) - end - -end - --- Handle responses to server requests -RegisterNetEvent(serverToClientBackToServerName, function(name, cbId, ...) - local data = cbData[cbId] - if not data then return end - - -- Process callback if provided - - if data.cb then - data.cb({...}) - end - -- Always resolve the promise with all args for direct returns - data.p:resolve({...}) - cbData[cbId] = nil -end) - exports('RegisterCallback', Callback.Register) exports('TriggerCallback', Callback.Trigger) - --- -- -- -- -- -- -- -- -- -- --- ▄▀▀ █ █ ██▀ █▄ █ ▀█▀ --- ▀▄▄ █▄▄ █ █▄▄ █ ▀█ █ --- -- -- -- -- -- -- -- -- -- -if IsDuplicityVersion() then return Callback end -::client:: - -cbRebounds = {} -function Callback.Register(name, callback) - Callback[name] = { - callback = callback, - } +if not IsDuplicityVersion() then + exports('RegisterRebound', Callback.RegisterRebound) end -function Callback.RegisterRebound(name, callback) - cbRebounds[name] = callback -end - --- Client to server trigger - supports both callback and direct return -function Callback.Trigger(name, callbackOrArg, ...) - -- Determine if the second parameter is a callback function or an argument - local hasCallback = type(callbackOrArg) == 'function' or (type(callbackOrArg) == 'table' and rawget(callbackOrArg, '__cfx_functionReference')) - local callback = hasCallback and callbackOrArg or nil - -- Adjust args based on whether the callback is present - local args = hasCallback and {...} or {callbackOrArg, ...} - - local cbId = name .. '_' .. math.random(1000000, 9999999) - local p = promise.new() - - -- Store promise data - cbData[cbId] = { - cb = callback, - p = p - } - - -- Trigger the server event - TriggerServerEvent(clientToServerName, name, cbId, table.unpack(args)) - - -- If no callback was provided, wait for the promise and return directly - if not hasCallback then - local result = Citizen.Await(p) - -- If there's only one value, return it directly - if #result == 1 then - return result[1] - else - return table.unpack(result) - end - end - - -- Otherwise, return nothing (callback will handle it) - return nil -end - --- Handle responses from server -RegisterNetEvent(clientToServerBackToClientName, function(name, cbId, ...) - -- Check for global rebounding callbacks - local clientRebound = cbRebounds[name] - if clientRebound then - clientRebound(...) - end - - -- Handle the specific callback instance - local data = cbData[cbId] - if not data then return end - - -- Process callback if provided - if data.cb then - data.cb(...) - end - - -- Always resolve the promise with all args for direct returns - data.p:resolve({...}) - cbData[cbId] = nil -end) - --- Handle server requests to client -RegisterNetEvent(serverToClientName, function(name, cbId, ...) - local data = Callback[name] - if not data then return end - local func = data.callback - if not func then return end - - -- Create response handler - TriggerServerEvent(serverToClientBackToServerName, name, cbId, func(...)) -end) - -exports('RegisterCallback', Callback.Register) -exports('RegisterRebound', Callback.RegisterRebound) -exports('TriggerCallback', Callback.Trigger) - -return Callback \ No newline at end of file +return Callback From 20b7b976a8d5313cc58d7c6f6dd3ff84317ba533 Mon Sep 17 00:00:00 2001 From: MrNewb <47620135+MrNewb@users.noreply.github.com> Date: Mon, 5 May 2025 14:57:02 -0400 Subject: [PATCH 11/15] Small patch --- fxmanifest.lua | 1 + lib/cache/shared/cache.lua | 7 +++---- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/fxmanifest.lua b/fxmanifest.lua index 48cfc4f..e9fec41 100644 --- a/fxmanifest.lua +++ b/fxmanifest.lua @@ -71,6 +71,7 @@ files { 'lib/**/client/*.lua', 'lib/**/shared/*.lua', 'lib/**/server/*.lua', + 'settings/*.lua', 'lib/init.lua', } diff --git a/lib/cache/shared/cache.lua b/lib/cache/shared/cache.lua index f80526a..ed42a50 100644 --- a/lib/cache/shared/cache.lua +++ b/lib/cache/shared/cache.lua @@ -1,5 +1,5 @@ local Cache = {} -local Config = require("lib/settings/clientConfig.lua") +local Config = Require("settings/sharedConfig.lua") local max = 5000 local CreateThread = CreateThread local Wait = Wait @@ -10,9 +10,8 @@ Cache.Caches = Cache.Caches or {} Cache.LoopRunning = Cache.LoopRunning or false local function print(...) - if Config.Debug then - print("^2[Cache]^0", ...) - end + if Config.DebugLevel == 0 then return end + print("^2[Cache]^0", ...) end local function StartLoop() From f913089d368681c1dcafe81e59129d60ae830904 Mon Sep 17 00:00:00 2001 From: JericoFX Date: Mon, 5 May 2025 19:24:17 -0300 Subject: [PATCH 12/15] add Client State Bag --- lib/init.lua | 4 +-- lib/statebags/client/client.lua | 48 +++++++++++++++++++++++++++++++++ lib/statebags/server/server.lua | 0 3 files changed, 50 insertions(+), 2 deletions(-) create mode 100644 lib/statebags/client/client.lua create mode 100644 lib/statebags/server/server.lua diff --git a/lib/init.lua b/lib/init.lua index 7d8cc5a..3d3df81 100644 --- a/lib/init.lua +++ b/lib/init.lua @@ -73,5 +73,5 @@ cLib.Particle = Particle or Require("lib/particles/client/particles.lua") cLib.Cache = Cache or Require("lib/cache/client/cache.lua") cLib.ClientEntity = ClientEntity or Require("lib/entities/client/client_entity.lua") cLib.ClientEntityActions = ClientEntityActions or Require("lib/entities/client/client_entity_actions.lua") - -return cLib \ No newline at end of file +cLib.ClientStateBag = ClientStateBag or Require("lib/statebags/client/client.lua") +return cLib diff --git a/lib/statebags/client/client.lua b/lib/statebags/client/client.lua new file mode 100644 index 0000000..0668718 --- /dev/null +++ b/lib/statebags/client/client.lua @@ -0,0 +1,48 @@ +ClientStateBag = {} + +---Gets an entity from a statebag name +---@param entityId string The entity ID or statebag name +---@return number|nil entity The entity handle or nil if not found +local function getStateBagEntity(entityId) + local _entity = GetEntityFromStateBagName(entityId) + return _entity +end + +local function getPlayerFromStateBagName(stateBagName) + return getPlayerFromStateBagName(stateBagName) +end + +---Adds a handler for entity statebag changes +---@param keyName string The statebag key to watch for changes +---@param entityId string|nil The specific entity ID to watch, or nil for all entities +---@param callback function The callback function to handle changes (function(entityId, key, value, lastValue, replicated)) +---@return number handler The handler ID +function ClientStateBag.AddEntityChangeHandler(keyName, entityId, callback) + return AddStateBagChangeHandler(keyName, entityId or nil, function(bagName, key, value, lastValue, replicated) + local entity = getStateBagEntity(bagName) + if not DoesEntityExist(entity) then return end + if entity then + return callback(entity, key, value, lastValue, replicated) + end + end) +end + +---Adds a handler for player statebag changes +---@param keyName string The statebag key to watch for changes +---@param filter boolean|nil If true, only watch for changes from the current player +---@param callback function The callback function to handle changes (function(playerId, key, value, lastValue, replicated)) +---@return number handler The handler ID +function ClientStateBag.AddPlayerChangeHandler(keyName, filter, callback) + return AddStateBagChangeHandler(keyName, filter and GetPlayerServerId(PlayerId()) or nil, + function(bagName, key, value, lastValue, replicated) + local actualPlayerId = getPlayerFromStateBagName(bagName) + if DoesEntityExist(actualPlayerId) and (not actualPlayerId == PlayerPedId()) then -- you cant have a statebag value if you are not the player + return false + end + if actualPlayerId and actualPlayerId ~= 0 then + return callback(tonumber(actualPlayerId), key, value, lastValue, replicated) + end + end) +end + +return ClientStateBag diff --git a/lib/statebags/server/server.lua b/lib/statebags/server/server.lua new file mode 100644 index 0000000..e69de29 From dc91f98e37d17519e7b84397281d4fe735b734b4 Mon Sep 17 00:00:00 2001 From: JericoFX Date: Mon, 5 May 2025 19:29:37 -0300 Subject: [PATCH 13/15] a little fix for the bag name --- lib/statebags/client/client.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/statebags/client/client.lua b/lib/statebags/client/client.lua index 0668718..2c2c364 100644 --- a/lib/statebags/client/client.lua +++ b/lib/statebags/client/client.lua @@ -33,10 +33,10 @@ end ---@param callback function The callback function to handle changes (function(playerId, key, value, lastValue, replicated)) ---@return number handler The handler ID function ClientStateBag.AddPlayerChangeHandler(keyName, filter, callback) - return AddStateBagChangeHandler(keyName, filter and GetPlayerServerId(PlayerId()) or nil, + return AddStateBagChangeHandler(keyName, filter and ("player:%s"):format(GetPlayerServerId(PlayerId())) or nil, function(bagName, key, value, lastValue, replicated) local actualPlayerId = getPlayerFromStateBagName(bagName) - if DoesEntityExist(actualPlayerId) and (not actualPlayerId == PlayerPedId()) then -- you cant have a statebag value if you are not the player + if DoesEntityExist(actualPlayerId) and (actualPlayerId ~= PlayerPedId()) then -- you cant have a statebag value if you are not the player return false end if actualPlayerId and actualPlayerId ~= 0 then From 11114bf52911a66550400cf8213b491ae2eb387a Mon Sep 17 00:00:00 2001 From: MrNewb <47620135+MrNewb@users.noreply.github.com> Date: Tue, 6 May 2025 14:39:29 -0400 Subject: [PATCH 14/15] core_inventory compatibility MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The current implementation isn’t the cleanest, but it gets the job done. I’ve had to rig parts of it together, and it hasn’t yet had a proper cleanup pass. This update adds support for core_inventory on both ESX and QB frameworks. Previously, the QB fallback worked fine, but an issue affecting ESX users was discovered. To resolve this, a change was needed in how framework-registered usable items are handled—allowing us to pass the item’s ID as the slot when using core_inventory, while maintaining slot-based behavior otherwise. This approach ensures compatibility without requiring any modifications to other resources. I've personally tested this on ESX, but since I haven’t been able to coordinate with the core_inventory team, QB Core users will essentially be the first wave of testers for this integration. --- modules/framework/es_extended/server.lua | 1 + modules/framework/qb-core/server.lua | 1 + modules/framework/qbx_core/server.lua | 1 + modules/inventory/core_inventory/client.lua | 28 +++++ modules/inventory/core_inventory/server.lua | 115 ++++++++++++++++++++ 5 files changed, 146 insertions(+) diff --git a/modules/framework/es_extended/server.lua b/modules/framework/es_extended/server.lua index 31fc9a8..4a1cfea 100644 --- a/modules/framework/es_extended/server.lua +++ b/modules/framework/es_extended/server.lua @@ -301,6 +301,7 @@ Framework.RegisterUsableItem = function(itemName, cb) local func = function(src, item, itemData) itemData = itemData or item itemData.metadata = itemData.metadata or itemData.info or {} + itemData.slot = itemData.id or itemData.slot cb(src, itemData) end ESX.RegisterUsableItem(itemName, func) diff --git a/modules/framework/qb-core/server.lua b/modules/framework/qb-core/server.lua index 6146517..1d81bc3 100644 --- a/modules/framework/qb-core/server.lua +++ b/modules/framework/qb-core/server.lua @@ -447,6 +447,7 @@ Framework.RegisterUsableItem = function(itemName, cb) local func = function(src, item, itemData) itemData = itemData or item itemData.metadata = itemData.metadata or itemData.info or {} + itemData.slot = itemData.id or itemData.slot cb(src, itemData) end QBCore.Functions.CreateUseableItem(itemName, func) diff --git a/modules/framework/qbx_core/server.lua b/modules/framework/qbx_core/server.lua index 2674f9d..aa614a6 100644 --- a/modules/framework/qbx_core/server.lua +++ b/modules/framework/qbx_core/server.lua @@ -413,6 +413,7 @@ Framework.RegisterUsableItem = function(itemName, cb) local func = function(src, item, itemData) itemData = itemData or item itemData.metadata = itemData.metadata or itemData.info or {} + itemData.slot = itemData.id or itemData.slot cb(src, itemData) end return QBox:CreateUseableItem(itemName, func) diff --git a/modules/inventory/core_inventory/client.lua b/modules/inventory/core_inventory/client.lua index 2e9cce0..f59f174 100644 --- a/modules/inventory/core_inventory/client.lua +++ b/modules/inventory/core_inventory/client.lua @@ -16,6 +16,34 @@ Inventory.GetImagePath = function(item) return imagePath or "https://avatars.githubusercontent.com/u/47620135" end +---comment +---@param item string +---@return boolean +Inventory.HasItem = function(item) + return core:hasItem(item, 1) +end + +---comment +---@param item string +---@return number +Inventory.GetItemCount = function(item) + return core:getItemCount(item) +end + +Inventory.GetPlayerInventory = function() + local playerItems = core:getInventory() + local repackedTable = {} + for _, v in pairs(playerItems) do + table.insert(repackedTable, { + name = v.name, + count = v.count, + metadata = v.metadata, + slot = v.id, + }) + end + return repackedTable +end + Inventory.GetItemInfo = function(item) local frameworkName = Framework.GetFrameworkName() if not frameworkName then return {} end diff --git a/modules/inventory/core_inventory/server.lua b/modules/inventory/core_inventory/server.lua index f4aa30d..65792dc 100644 --- a/modules/inventory/core_inventory/server.lua +++ b/modules/inventory/core_inventory/server.lua @@ -14,6 +14,121 @@ Inventory.GetImagePath = function(item) return imagePath or "https://avatars.githubusercontent.com/u/47620135" end +---This will add an item, and return true or false based on success +---@param src number +---@param item string +---@param count number +---@param slot number +---@param metadata table +---@return boolean +Inventory.AddItem = function(src, item, count, slot, metadata) + TriggerClientEvent("community_bridge:client:inventory:updateInventory", src, {action = "add", item = item, count = count, slot = slot, metadata = metadata}) + local itemsAdd = core:addItem(src, item, count, metadata) + return itemsAdd +end + +Inventory.GetPlayerInventory = function(src) + local playerItems = core:getInventory(src) + local repackedTable = {} + for _, v in pairs(playerItems) do + table.insert(repackedTable, { + name = v.name, + count = v.count, + metadata = v.metadata, + slot = v.id, + }) + end + return repackedTable +end + +Inventory.RemoveItem = function(src, item, count, slot, metadata) + if not slot and metadata then + local inv = Inventory.GetPlayerInventory(src) + if not inv then return false end + for _, v in pairs(inv) do + if v.name == item and v.metadata == metadata then + slot = v.slot + break + end + end + end + TriggerClientEvent("community_bridge:client:inventory:updateInventory", src, {action = "remove", item = item, count = count, slot = slot, metadata = metadata}) + if slot then + local identifier = Framework.GetPlayerIdentifier(src) + if not identifier then return false end + local framework = Bridge.Framework.GetFrameworkName() + if framework == 'es_extended' then + identifier = string.gsub(identifier, ":", "") + end + local weirdInventoryName = 'content-' .. identifier + return core:removeItemExact(weirdInventoryName, slot, count) + end + core:removeItem(src, item, count) + return true + -- I hate this inventory so much, I am so sorry for this. +end + +---This will get the item from the specified slot. +---@param src number +---@param slot number +---@return table +Inventory.GetItemBySlot = function(src, slot) + local inv = Inventory.GetPlayerInventory(src) + if not inv then return {} end + for _, v in pairs(inv) do + print(v.slot, slot) + if v.slot == slot then + return { + name = v.name, + count = v.count, + metadata = v.metadata, + slot = v.slot, + } + end + end + return {} +end + +---Returns the total count of an item in the inventory. +---@param src number +---@param item string +---@param metadata table +---@return number +Inventory.GetItemCount = function(src, item, metadata) + if metadata then + local inv = Inventory.GetPlayerInventory(src) + local deepCount = 0 + if not inv then return 0 end + for _, v in pairs(inv) do + if v.name == item and v.metadata == metadata then + deepCount = deepCount + v.count + end + end + return deepCount + end + local count = core:getItemCount(src, item) + return count or 0 +end + +---Returns boolean if the player has the item in their inventory. +---@param src number +---@param item string +---@return boolean +Inventory.HasItem = function(src, item) + local count = core:getItemCount(src, item) + return count > 0 +end + +---This will set the metadata of an item in the inventory. +---@param src number +---@param item string +---@param slot number +---@param metadata table +---@return nil +Inventory.SetMetadata = function(src, item, slot, metadata) + core:setMetadata(src, slot, metadata) +end + ---comment ---@param oldplate string ---@param newplate string From 97c7d290b9892d250f409fc1e49dc917664ebaec Mon Sep 17 00:00:00 2001 From: MrNewb <47620135+MrNewb@users.noreply.github.com> Date: Tue, 6 May 2025 14:48:22 -0400 Subject: [PATCH 15/15] feat: add new features and functionality, bump version for upcoming main push --- fxmanifest.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/fxmanifest.lua b/fxmanifest.lua index e9fec41..4668f29 100644 --- a/fxmanifest.lua +++ b/fxmanifest.lua @@ -3,8 +3,9 @@ game 'gta5' lua54 'yes' use_experimental_fxv2_oal 'yes' author 'The Order of the Sacred Framework' -description 'A bridge made for the community to use as a base for their own projects. This bridge will allow a single format to work with nearly all commonly used systems while still offering expandability.' -version '0.6.1' +name 'community_bridge' +description 'A Universal Bridge for Our Community, created by a group of contributors with a shared vision to enhance both user and developer experiences. This bridge connects various frameworks, inventories, target systems, notification systems, and more, fostering compatibility and seamless integration.' +version '0.7.0' shared_scripts { '@ox_lib/init.lua',