From 2ff8382eb43471e604d49fc8cf693a246d417c65 Mon Sep 17 00:00:00 2001 From: Linden <65407488+thelindat@users.noreply.github.com> Date: Mon, 28 Feb 2022 06:39:56 +0000 Subject: [PATCH 01/10] refactor: update ox_lib syntax for v2.0.0 --- client.lua | 24 +++++++++++------------- modules/interface/client.lua | 6 ++---- modules/inventory/server.lua | 20 ++++++++++---------- modules/shops/server.lua | 6 ++---- server.lua | 13 ++++++------- 5 files changed, 31 insertions(+), 38 deletions(-) diff --git a/client.lua b/client.lua index 293dbb8e93..bab7d2abb6 100644 --- a/client.lua +++ b/client.lua @@ -51,7 +51,6 @@ local function CloseTrunk() end end -local ServerCallback = lib.callbacks local Interface = client.interface local plyState = LocalPlayer.state @@ -74,7 +73,7 @@ local function OpenInventory(inv, data) local left, right if inv == 'shop' and invOpen == false then - left, right = ServerCallback.Await(shared.resource, 'openShop', 200, data) + left, right = lib.callback.await('ox_inventory:openShop', 200, data) elseif invOpen ~= nil then if inv == 'policeevidence' then local input = Interface.Keyboard(shared.locale('police_evidence'), {shared.locale('locker_number')}) @@ -92,7 +91,7 @@ local function OpenInventory(inv, data) end end - left, right = ServerCallback.Await(shared.resource, 'openInventory', false, inv, data) + left, right = lib.callback.await('ox_inventory:openInventory', false, inv, data) end if left then @@ -138,7 +137,7 @@ local function useItem(data, cb) if currentWeapon and currentWeapon?.timer > 100 then return end invBusy = true - local result = ServerCallback.Await(shared.resource, 'useItem', 200, data.name, data.slot, PlayerData.inventory[data.slot].metadata) + local result = lib.callback.await('ox_inventory:useItem', 200, data.name, data.slot, PlayerData.inventory[data.slot].metadata) if not result then Wait(500) @@ -748,7 +747,6 @@ RegisterNetEvent('ox_inventory:removeDrop', function(id) end) local uiLoaded = false -local DisableControlActions = lib.controls local function setStateBagHandler(id) AddStateBagChangeHandler(nil, 'player:'..id, function(bagName, key, value, _, _) @@ -757,9 +755,9 @@ local function setStateBagHandler(id) elseif key == 'invBusy' then invBusy = value if value then - DisableControlActions:Add(23, 25, 36, 263) + lib.disableControls:Add(23, 25, 36, 263) else - DisableControlActions:Remove(23, 25, 36, 263) + lib.disableControls:Remove(23, 25, 36, 263) end elseif key == 'instance' then currentInstance = value @@ -947,7 +945,7 @@ RegisterNetEvent('ox_inventory:setPlayerInventory', function(currentDrops, inven end, 200) local EnableKeys = client.enablekeys - client.tick = SetInterval(function() + client.tick = SetInterval(function(disableControls) local playerPed = PlayerData.ped DisablePlayerVehicleRewards(PlayerData.id) @@ -964,7 +962,7 @@ RegisterNetEvent('ox_inventory:setPlayerInventory', function(currentDrops, inven EnableControlAction(0, 31, true) end else - DisableControlActions() + disableControls() if invBusy then DisablePlayerFiring(PlayerData.id, true) end for _, v in pairs(nearbyMarkers) do @@ -974,7 +972,7 @@ RegisterNetEvent('ox_inventory:setPlayerInventory', function(currentDrops, inven if closestMarker and IsControlJustReleased(0, 38) then if closestMarker[3] == 'license' then - ServerCallback.Async(shared.resource, 'buyLicense', 1000, function(success, message) + lib.callback.Async(shared.resource, 'buyLicense', 1000, function(success, message) if success == false then Utils.Notify({type = 'error', text = shared.locale(message), duration = 2500}) else @@ -1047,7 +1045,7 @@ RegisterNetEvent('ox_inventory:setPlayerInventory', function(currentDrops, inven end end end - end) + end, 0, lib.disableControls) collectgarbage('collect') end) @@ -1162,7 +1160,7 @@ RegisterNUICallback('swapItems', function(data, cb) data.instance = currentInstance end - local success, response, weapon = ServerCallback.Await(shared.resource, 'swapItems', false, data) + local success, response, weapon = lib.callback.await('ox_inventory:swapItems', false, data) if response then updateInventory(response.items, response.weight) @@ -1181,7 +1179,7 @@ RegisterNUICallback('swapItems', function(data, cb) end) RegisterNUICallback('buyItem', function(data, cb) - local response, data, message = ServerCallback.Await(shared.resource, 'buyItem', 100, data) + local response, data, message = lib.callback.await('ox_inventory:buyItem', 100, data) if data then PlayerData.inventory[data[1]] = data[2] client.setPlayerData('inventory', PlayerData.inventory) diff --git a/modules/interface/client.lua b/modules/interface/client.lua index 32c7d823e9..714894efdc 100644 --- a/modules/interface/client.lua +++ b/modules/interface/client.lua @@ -42,8 +42,6 @@ local progress = { Interface.ProgressActive = false -local DisableControlActions = lib.controls - local function ResetPlayer() if progress.anim or progress.scenario then ClearPedTasks(PlayerData.ped) @@ -58,7 +56,7 @@ local function ResetPlayer() end end - if #progress.disable > 0 then DisableControlActions:Remove(progress.disable) end + if #progress.disable > 0 then lib.disableControls:Remove(progress.disable) end table.wipe(progress.disable) Interface.ProgressActive = false progress.anim = false @@ -93,7 +91,7 @@ function Interface.Progress(options, completed) end end end - if count > 0 then DisableControlActions:Add(progress.disable) end + if count > 0 then disableControls:Add(progress.disable) end end Interface.ProgressActive = true diff --git a/modules/inventory/server.lua b/modules/inventory/server.lua index 4d3bcaf0db..eebfcd79ba 100644 --- a/modules/inventory/server.lua +++ b/modules/inventory/server.lua @@ -1048,7 +1048,7 @@ RegisterServerEvent('ox_inventory:updateWeapon', function(action, value, slot) end end) -import.commands('ox_inventory', {'additem', 'giveitem'}, function(source, args) +lib.addCommand('ox_inventory', {'additem', 'giveitem'}, function(source, args) args.item = Items(args.item) if args.item and args.count > 0 then Inventory.AddItem(args.target, args.item.name, args.count, args.metatype) @@ -1063,7 +1063,7 @@ import.commands('ox_inventory', {'additem', 'giveitem'}, function(source, args) end end, {'target:number', 'item:string', 'count:number', 'metatype:?string'}) -import.commands('ox_inventory', 'removeitem', function(source, args) +lib.addCommand('ox_inventory', 'removeitem', function(source, args) args.item = Items(args.item) if args.item and args.count > 0 then Inventory.RemoveItem(args.target, args.item.name, args.count, args.metaType) @@ -1078,7 +1078,7 @@ import.commands('ox_inventory', 'removeitem', function(source, args) end end, {'target:number', 'item:string', 'count:number', 'metatype:?string'}) -import.commands('ox_inventory', 'setitem', function(source, args) +lib.addCommand('ox_inventory', 'setitem', function(source, args) args.item = Items(args.item) if args.item and args.count >= 0 then Inventory.SetItem(args.target, args.item.name, args.count, args.metaType) @@ -1093,7 +1093,7 @@ import.commands('ox_inventory', 'setitem', function(source, args) end end, {'target:number', 'item:string', 'count:number', 'metatype:?string'}) -import.commands(false, 'clearevidence', function(source, args) +lib.addCommand(false, 'clearevidence', function(source, args) local inventory = Inventories[source] local hasPermission = false @@ -1109,28 +1109,28 @@ import.commands(false, 'clearevidence', function(source, args) end end, {'evidence:number'}) -import.commands('ox_inventory', 'takeinv', function(source, args) +lib.addCommand('ox_inventory', 'takeinv', function(source, args) Inventory.Confiscate(args.target) end, {'target:number'}) -import.commands('ox_inventory', 'returninv', function(source, args) +lib.addCommand('ox_inventory', 'returninv', function(source, args) Inventory.Return(args.target) end, {'target:number'}) -import.commands('ox_inventory', 'clearinv', function(source, args) +lib.addCommand('ox_inventory', 'clearinv', function(source, args) Inventory.Clear(args.target) end, {'target:number'}) -import.commands('ox_inventory', 'saveinv', function() +lib.addCommand('ox_inventory', 'saveinv', function() saveInventories() end) -import.commands('ox_inventory', 'viewinv', function(source, args) +lib.addCommand('ox_inventory', 'viewinv', function(source, args) local inventory = Inventories[args.target] or Inventories[tonumber(args.target)] TriggerClientEvent('ox_inventory:viewInventory', source, inventory) end, {'target'}) -import.commands = nil +lib.addCommand = nil Inventory.accounts = server.accounts TriggerEvent('ox_inventory:loadInventory', Inventory) diff --git a/modules/shops/server.lua b/modules/shops/server.lua index 202fabe553..415c754bdd 100644 --- a/modules/shops/server.lua +++ b/modules/shops/server.lua @@ -67,9 +67,7 @@ for shopName, shopDetails in pairs(data('shops')) do end end -local ServerCallback = lib.callbacks - -ServerCallback.Register('openShop', function(source, data) +lib.callback.register('ox_inventory:openShop', function(source, data) local left, shop = Inventory(source) if data then shop = data.id and Shops[data.type][data.id] or Shops[data.type] @@ -99,7 +97,7 @@ local function comma_value(n) return left..(num:reverse():gsub('(%d%d%d)','%1,'):reverse())..right end -ServerCallback.Register('buyItem', function(source, data) +lib.callback.register('ox_inventory:buyItem', function(source, data) if data.toType == 'player' then if data.count == nil then data.count = 1 end local playerInv = Inventory(source) diff --git a/server.lua b/server.lua index 5446ea2273..f6256b946d 100644 --- a/server.lua +++ b/server.lua @@ -46,10 +46,9 @@ AddEventHandler('ox_inventory:setPlayerInventory', setPlayerInventory) local Stashes = data 'stashes' local Vehicles = data 'vehicles' -local ServerCallback = lib.callbacks local table = lib.table -ServerCallback.Register('openInventory', function(source, inv, data) +lib.callback.register('ox_inventory:openInventory', function(source, inv, data) local left = Inventory(source) local right = left.open and Inventory(left.open) @@ -156,7 +155,7 @@ end) local Log = server.logs -ServerCallback.Register('swapItems', function(source, data) +lib.callback.register('ox_inventory:swapItems', function(source, data) -- TODO: requires re-re-re-refactor and helper functions to reduce repetition if data.count > 0 and data.toType ~= 'shop' then local playerInventory, items, ret = Inventory(source), {}, nil @@ -424,7 +423,7 @@ end) local Licenses = data 'licenses' -ServerCallback.Register('buyLicense', function(source, id) +lib.callback.register('ox_inventory:buyLicense', function(source, id) if shared.framework == 'esx' then local license = Licenses[id] if license then @@ -445,12 +444,12 @@ ServerCallback.Register('buyLicense', function(source, id) end end) -ServerCallback.Register('getItemCount', function(source, item, metadata, target) +lib.callback.register('ox_inventory:getItemCount', function(source, item, metadata, target) local inventory = target and Inventory(target) or Inventory(source) return (inventory and Inventory.GetItem(inventory, item, metadata, true)) or 0 end) -ServerCallback.Register('getInventory', function(source, id) +lib.callback.register('ox_inventory:getInventory', function(source, id) local inventory = Inventory(id or source) return inventory and { id = inventory.id, @@ -464,7 +463,7 @@ ServerCallback.Register('getInventory', function(source, id) } end) -ServerCallback.Register('useItem', function(source, item, slot, metadata) +lib.callback.register('ox_inventory:useItem', function(source, item, slot, metadata) local inventory = Inventory(source) if inventory.type == 'player' then local item, type = Items(item) From 1ee64e2855ddf365e3812ebee9b43aebf6343b18 Mon Sep 17 00:00:00 2001 From: Linden <65407488+thelindat@users.noreply.github.com> Date: Mon, 28 Feb 2022 22:37:37 +0000 Subject: [PATCH 02/10] refactor(server): change identifiers for owned stashes Introduce dbcleanup.lua to modify table, changing their names from 'stashowner' i.e. 'example_stash2bobsmith' to just 'example_stash2'. When an inventory is loaded, its unique id (as above) will be set, but includes : as a delimiter (example_stash2:bobsmith). --- fxmanifest.lua | 6 +++--- modules/inventory/server.lua | 16 +++++++++++++++- server.lua | 9 ++++----- setup/convert.lua | 3 ++- setup/dbcleanup.lua | 23 +++++++++++++++++++++++ 5 files changed, 47 insertions(+), 10 deletions(-) create mode 100644 setup/dbcleanup.lua diff --git a/fxmanifest.lua b/fxmanifest.lua index bd685e9711..cda5c58d62 100644 --- a/fxmanifest.lua +++ b/fxmanifest.lua @@ -7,7 +7,7 @@ game 'gta5' --[[ Resource Information ]]-- name 'ox_inventory' author 'Overextended' -version '2.4.5' +version '2.5.0' repository 'https://github.com/overextended/ox_inventory' description 'Slot-based inventory with metadata' @@ -46,10 +46,10 @@ server_scripts { 'modules/inventory/server.lua', 'modules/shops/server.lua', 'server.lua', + -- 'setup/convert.lua', + 'setup/dbcleanup.lua', } ---server_script 'setup/convert.lua' - ui_page 'web/build/index.html' files { diff --git a/modules/inventory/server.lua b/modules/inventory/server.lua index eebfcd79ba..714d7e7de8 100644 --- a/modules/inventory/server.lua +++ b/modules/inventory/server.lua @@ -164,6 +164,10 @@ function Inventory.Create(id, label, invType, slots, weight, maxWeight, owner, i time = os.time() } + if self.type ~= 'player' and self.owner and type(self.owner) ~= 'boolean' then + self.id = ('%s:%s'):format(self.id, self.owner) + end + if self.type == 'drop' then self.datastore = true else @@ -211,8 +215,18 @@ function Inventory.Save(inv) elseif inv.type == 'glovebox' then MySQL.prepare('UPDATE owned_vehicles SET glovebox = ? WHERE plate = ?', { inventory, Inventory.GetPlateFromId(inv.id) }) else + local dbId + + if inv.owner and inv.owner ~= true then + dbId = inv.id:sub(-#inv.owner, #inv.id) + + if dbId == inv.owner then + dbId = inv.id:sub(0, #inv.id - #dbId - 1) + end + end + MySQL.prepare('INSERT INTO ox_inventory (owner, name, data) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE data = VALUES(data)', { - inv.owner or '', inv.id, inventory, + inv.owner or '', dbId, inventory, }) end inv.changed = false diff --git a/server.lua b/server.lua index f6256b946d..74f3925431 100644 --- a/server.lua +++ b/server.lua @@ -67,10 +67,10 @@ lib.callback.register('ox_inventory:openInventory', function(source, inv, data) if not stash.groups or server.hasGroup(left, stash.groups) then local owner = stash.owner and left.owner or stash.owner - right = Inventory(owner and stash.name..owner or stash.name) + right = Inventory(stash.name) if not right then - right = Inventory.Create(owner and stash.name..owner or stash.name, stash.label or stash.name, inv, stash.slots, 0, stash.weight, owner or false) + right = Inventory.Create(stash.name, stash.label or stash.name, inv, stash.slots, 0, stash.weight, owner or false) end end @@ -79,11 +79,10 @@ lib.callback.register('ox_inventory:openInventory', function(source, inv, data) if stash then if not stash.groups or server.hasGroup(left, stash.groups) then local owner = (stash.owner == nil and nil) or (type(stash.owner) == 'string' and stash.owner) or data.owner or stash.owner and left.owner - data = (owner and ('%s%s'):format(data.id or data, owner)) or data.id or data - right = Inventory(data) + right = Inventory(data.id or data) if not right then - right = Inventory.Create(data, stash.label or stash.name, inv, stash.slots, 0, stash.weight, owner or false) + right = Inventory.Create(data.id or data, stash.label or stash.name, inv, stash.slots, 0, stash.weight, owner or false) end end diff --git a/setup/convert.lua b/setup/convert.lua index 8d638532c1..a22dfe65fb 100644 --- a/setup/convert.lua +++ b/setup/convert.lua @@ -132,8 +132,9 @@ CreateThread(function() shared.ready = false Print([[Currently running in setup mode If you are upgrading from linden_inventory, type '/convertinventory linden' +To update standard ESX player inventories to support metadata, type '/convertinventory' -To update standard ESX player inventories to support metadata, type '/convertinventory']]) +Remove 'setup/convert.lua' from fxmanifest.lua and restart the server when you are done]]) RegisterCommand('convertinventory', function(source, args, raw) if not started then diff --git a/setup/dbcleanup.lua b/setup/dbcleanup.lua new file mode 100644 index 0000000000..e2b43b040f --- /dev/null +++ b/setup/dbcleanup.lua @@ -0,0 +1,23 @@ +-- Clean up ox_inventory table in the database +-- Used when upgrading to 2.5.0 from a previous release + +CreateThread(function() + local result = MySQL.query.await("SELECT owner, name FROM ox_inventory WHERE NOT owner = ''") + local parameters = {} + + for i = 1, #result do + local data = result[i] + local snip = data.name:sub(-#data.owner, #data.name) + + if data.owner == snip then + data.name = data.name:sub(0, #data.name - #snip) + parameters[i] = { data.name, snip } + end + end + + if #parameters > 1 then + MySQL.prepare.await("UPDATE ox_inventory SET name = ? WHERE owner = ?", parameters) + else + print("Remove 'setup/dbcleanup.lua' from fxmanifest.lua") + end +end) From bb6aab02689e4450a3bc22043aaca70284141f1e Mon Sep 17 00:00:00 2001 From: Linden <65407488+thelindat@users.noreply.github.com> Date: Mon, 28 Feb 2022 23:09:00 +0000 Subject: [PATCH 03/10] refactor(server/inventory): store dbId --- modules/inventory/server.lua | 25 ++++++++----------------- 1 file changed, 8 insertions(+), 17 deletions(-) diff --git a/modules/inventory/server.lua b/modules/inventory/server.lua index 714d7e7de8..aa1b79f17b 100644 --- a/modules/inventory/server.lua +++ b/modules/inventory/server.lua @@ -161,21 +161,22 @@ function Inventory.Create(id, label, invType, slots, weight, maxWeight, owner, i set = Inventory.Set, get = Inventory.Get, minimal = minimal, - time = os.time() + time = os.time(), } - if self.type ~= 'player' and self.owner and type(self.owner) ~= 'boolean' then - self.id = ('%s:%s'):format(self.id, self.owner) - end - if self.type == 'drop' then self.datastore = true else self.changed = false + self.dbId = self.id + + if self.type ~= 'player' and self.owner and type(self.owner) ~= 'boolean' then + self.id = ('%s:%s'):format(self.id, self.owner) + end end if not self.items then - self.items, self.weight, self.datastore = Inventory.Load(self.id, self.type, self.owner) + self.items, self.weight, self.datastore = Inventory.Load(self.dbId, self.type, self.owner) elseif self.weight == 0 and next(self.items) then self.weight = Inventory.CalculateWeight(self.items) end @@ -215,18 +216,8 @@ function Inventory.Save(inv) elseif inv.type == 'glovebox' then MySQL.prepare('UPDATE owned_vehicles SET glovebox = ? WHERE plate = ?', { inventory, Inventory.GetPlateFromId(inv.id) }) else - local dbId - - if inv.owner and inv.owner ~= true then - dbId = inv.id:sub(-#inv.owner, #inv.id) - - if dbId == inv.owner then - dbId = inv.id:sub(0, #inv.id - #dbId - 1) - end - end - MySQL.prepare('INSERT INTO ox_inventory (owner, name, data) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE data = VALUES(data)', { - inv.owner or '', dbId, inventory, + inv.owner or '', inv.dbId, inventory, }) end inv.changed = false From d840b9eddf8bb535568bb5e52f16cba0ecdebc1e Mon Sep 17 00:00:00 2001 From: Linden <65407488+thelindat@users.noreply.github.com> Date: Tue, 1 Mar 2022 00:44:38 +0000 Subject: [PATCH 04/10] fix(server/inventory): incorrect id sent to Inventory.Remove --- modules/inventory/server.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/inventory/server.lua b/modules/inventory/server.lua index aa1b79f17b..bc5117fb99 100644 --- a/modules/inventory/server.lua +++ b/modules/inventory/server.lua @@ -889,7 +889,7 @@ SetInterval(function() end if (inv.datastore or inv.owner) and time - inv.time >= 3000 then - Inventory.Remove(id, inv.type) + Inventory.Remove(inv.id, inv.type) end end end From 75d39affafa4fd85d672722b4c37a85923a5c31b Mon Sep 17 00:00:00 2001 From: Linden <65407488+thelindat@users.noreply.github.com> Date: Tue, 1 Mar 2022 10:54:52 +0000 Subject: [PATCH 05/10] fix(server/inventory): incorrect id referenced during prepareSave --- modules/init.lua | 6 +++--- modules/inventory/server.lua | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/init.lua b/modules/init.lua index 4d4b51537f..1f4fa68700 100644 --- a/modules/init.lua +++ b/modules/init.lua @@ -83,16 +83,16 @@ if not SetInterval or not import then error('Ox Inventory requires the ox_lib resource, refer to the documentation.') end -if not lib.checkDependency('oxmysql', '2.0.0') or not lib.checkDependency('ox_lib', '1.5.0') then error() end +if not lib.checkDependency('oxmysql', '2.0.0') or not lib.checkDependency('ox_lib', '2.0.0') then error() end if not LoadResourceFile(shared.resource, 'web/build/index.html') then - error('Unable to locate ox_inventory/web/build, refer to the documentation or download a release build.') + error('UI has not been built, refer to the documentation or download a release build.') end -- Disable qtarget compatibility if it isn't running if shared.qtarget and not GetResourceState('qtarget'):find('start') then shared.qtarget = false - shared.warning(("qtarget compatibility has been disabled, resource state is '%s'"):format(GetResourceState('qtarget'))) + shared.warning(("qtarget is '%s' - ensure it is starting before ox_inventory"):format(GetResourceState('qtarget'))) end if shared.server then shared.ready = false end diff --git a/modules/inventory/server.lua b/modules/inventory/server.lua index bc5117fb99..562a9b1e16 100644 --- a/modules/inventory/server.lua +++ b/modules/inventory/server.lua @@ -871,7 +871,7 @@ local function prepareSave(inv) elseif inv.type == 'glovebox' then return 2, { json.encode(minimal(inv)), Inventory.GetPlateFromId(inv.id) } else - return 3, { inv.owner or '', inv.id, json.encode(minimal(inv)) } + return 3, { inv.owner or '', inv.dbId, json.encode(minimal(inv)) } end end From 4b851e708019e8c19478080a400bb1aabaf19884 Mon Sep 17 00:00:00 2001 From: Linden <65407488+thelindat@users.noreply.github.com> Date: Tue, 1 Mar 2022 11:16:06 +0000 Subject: [PATCH 06/10] refactor(init): check for lib --- modules/init.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/init.lua b/modules/init.lua index 1f4fa68700..c59da6aaaa 100644 --- a/modules/init.lua +++ b/modules/init.lua @@ -79,7 +79,7 @@ function data(name) return func() end -if not SetInterval or not import then +if not lib then error('Ox Inventory requires the ox_lib resource, refer to the documentation.') end From 539eb6e5205579ef23c2475bbe36f102a94f390b Mon Sep 17 00:00:00 2001 From: Linden <65407488+thelindat@users.noreply.github.com> Date: Tue, 1 Mar 2022 15:01:20 +0000 Subject: [PATCH 07/10] refactor(client): use ox_lib's cache --- client.lua | 134 ++++++++++++++++++++++------------------------------- 1 file changed, 56 insertions(+), 78 deletions(-) diff --git a/client.lua b/client.lua index bab7d2abb6..576e6e8e01 100644 --- a/client.lua +++ b/client.lua @@ -22,10 +22,10 @@ local function CanOpenInventory() return PlayerData.loaded and not invBusy and not PlayerData.dead - and not GetPedConfigFlag(PlayerData.ped, 120, true) + and not GetPedConfigFlag(cache.ped, 120, true) and (currentWeapon == nil or currentWeapon.timer == 0) and not IsPauseMenuActive() - and not IsPedFatallyInjured(PlayerData.ped) + and not IsPedFatallyInjured(cache.ped) and invOpen ~= nil end @@ -40,8 +40,8 @@ local currentInventory = defaultInventory local function CloseTrunk() if currentInventory?.type == 'trunk' then - local coords = GetEntityCoords(PlayerData.ped, true) - Utils.PlayAnimAdvanced(900, 'anim@heists@fleeca_bank@scope_out@return_case', 'trevor_action', coords.x, coords.y, coords.z, 0.0, 0.0, GetEntityHeading(PlayerData.ped), 2.0, 2.0, 1000, 49, 0.25) + local coords = GetEntityCoords(cache.ped, true) + Utils.PlayAnimAdvanced(900, 'anim@heists@fleeca_bank@scope_out@return_case', 'trevor_action', coords.x, coords.y, coords.z, 0.0, 0.0, GetEntityHeading(cache.ped), 2.0, 2.0, 1000, 49, 0.25) CreateThread(function() local entity = currentInventory.entity local door = currentInventory.door @@ -95,7 +95,7 @@ local function OpenInventory(inv, data) end if left then - if inv ~= 'trunk' and not IsPedInAnyVehicle(PlayerData.ped, false) then + if inv ~= 'trunk' and not IsPedInAnyVehicle(cache.ped, false) then Utils.PlayAnim(1000, 'pickup_object', 'putdown_low', 5.0, 1.5, -1, 48, 0.0, 0, 0, 0) end plyState.invOpen = true @@ -115,7 +115,7 @@ local function OpenInventory(inv, data) }) if not currentInventory.coords and not inv == 'container' then - currentInventory.coords = GetEntityCoords(PlayerData.ped) + currentInventory.coords = GetEntityCoords(cache.ped) end -- Stash exists (useful for custom stashes) @@ -133,7 +133,7 @@ exports('openInventory', OpenInventory) local function useItem(data, cb) if invOpen and data.close then TriggerEvent('ox_inventory:closeInventory') end - if not invBusy and not Interface.ProgressActive and not IsPedRagdoll(PlayerData.ped) and not IsPedFalling(PlayerData.ped) then + if not invBusy and not Interface.ProgressActive and not IsPedRagdoll(cache.ped) and not IsPedFalling(cache.ped) then if currentWeapon and currentWeapon?.timer > 100 then return end invBusy = true @@ -234,7 +234,7 @@ local function useSlot(slot) return end - local playerPed = PlayerData.ped + local playerPed = cache.ped ClearPedSecondaryTask(playerPed) if data.throwable then item.throwable = true end if currentWeapon then currentWeapon = Utils.Disarm(currentWeapon) end @@ -289,7 +289,7 @@ local function useSlot(slot) end end) elseif currentWeapon then - local playerPed = PlayerData.ped + local playerPed = cache.ped if item.name:sub(0, 5) == 'ammo-' then if client.weaponWheel then return end local maxAmmo = GetMaxAmmoInClip(playerPed, currentWeapon.hash, true) @@ -454,8 +454,8 @@ local function RegisterCommands() if StashTarget then OpenInventory('stash', StashTarget) - elseif PlayerData.currentVehicle then - local vehicle = PlayerData.currentVehicle + elseif cache.vehicle then + local vehicle = cache.vehicle if NetworkGetEntityIsNetworked(vehicle) then local checkVehicle = Vehicles.Storage[GetEntityModel(vehicle)] @@ -469,7 +469,7 @@ local function RegisterCommands() while true do Wait(100) if not invOpen then break - elseif not IsPedInAnyVehicle(PlayerData.ped, false) then + elseif not IsPedInAnyVehicle(cache.ped, false) then TriggerEvent('ox_inventory:closeInventory') break end @@ -525,7 +525,7 @@ local function RegisterCommands() if closeToVehicle then local plate = client.trimplate and string.strtrim(GetVehicleNumberPlateText(vehicle)) or GetVehicleNumberPlateText(vehicle) - TaskTurnPedToFaceCoord(PlayerData.ped, position.x, position.y, position.z) + TaskTurnPedToFaceCoord(cache.ped, position.x, position.y, position.z) lastVehicle = vehicle OpenInventory('trunk', {id='trunk'..plate, class=class, model=vehHash}) local timeout = 20 @@ -550,9 +550,9 @@ local function RegisterCommands() if closeToVehicle and invOpen then position = GetWorldPositionOfEntityBone(vehicle, vehBone) - if #(GetEntityCoords(PlayerData.ped) - position) >= 2 or not DoesEntityExist(vehicle) then + if #(GetEntityCoords(cache.ped) - position) >= 2 or not DoesEntityExist(vehicle) then break - else TaskTurnPedToFaceCoord(PlayerData.ped, position.x, position.y, position.z) end + else TaskTurnPedToFaceCoord(cache.ped, position.x, position.y, position.z) end else break end end @@ -726,10 +726,10 @@ RegisterNetEvent('ox_inventory:createDrop', function(drop, data, owner, slot) drops[drop] = data end - if owner == PlayerData.source and invOpen and #(GetEntityCoords(PlayerData.ped) - data.coords) <= 1 then + if owner == PlayerData.source and invOpen and #(GetEntityCoords(cache.ped) - data.coords) <= 1 then if currentWeapon?.slot == slot then currentWeapon = Utils.Disarm(currentWeapon) end - if not IsPedInAnyVehicle(PlayerData.ped, false) then + if not IsPedInAnyVehicle(cache.ped, false) then OpenInventory('drop', drop) else SendNUIMessage({ @@ -772,12 +772,16 @@ end RegisterNetEvent('ox_inventory:setPlayerInventory', function(currentDrops, inventory, weight, esxItem, player, source) PlayerData = player - PlayerData.id = PlayerId() - PlayerData.ped = PlayerPedId() + PlayerData.id = cache.playerId PlayerData.source = source - PlayerData.dead = false - PlayerData.cuffed = false - PlayerData.loaded = false + + setmetatable(PlayerData, { + __index = function(self, key) + if key == 'ped' then + return cache.ped + else return false end + end + }) if setStateBagHandler then setStateBagHandler(source) end @@ -824,7 +828,7 @@ RegisterNetEvent('ox_inventory:setPlayerInventory', function(currentDrops, inven locale = locales, items = ItemData, leftInventory = { - id = PlayerData.id, + id = cache.playerId, slots = shared.playerslots, items = PlayerData.inventory, maxWeight = shared.playerweight, @@ -846,50 +850,33 @@ RegisterNetEvent('ox_inventory:setPlayerInventory', function(currentDrops, inven Utils.Notify({text = shared.locale('inventory_setup'), duration = 2500}) local Licenses = data 'licenses' - client.interval = SetInterval(function() - local playerPed = PlayerPedId() + lib.onCache('ped', function() + Utils.WeaponWheel(client.weaponWheel) + end) - if playerPed ~= PlayerData.ped then - PlayerData.ped = playerPed - Utils.WeaponWheel(client.weaponWheel) + lib.onCache('vehicle', function(vehicle) + if vehicle then + if DoesVehicleHaveWeapons(vehicle) then + return Utils.WeaponWheel(true) + -- todo: check if current seat has weapon + end end - if invOpen == false then - playerCoords = GetEntityCoords(playerPed) - local vehicle = GetVehiclePedIsIn(playerPed, false) - - if vehicle == 0 then vehicle = nil end - - if PlayerData.currentVehicle ~= vehicle then - PlayerData.currentVehicle = vehicle - - if vehicle then - -- local seats = GetVehicleMaxNumberOfPassengers(vehicle) - 1 - - if DoesVehicleHaveWeapons(vehicle) then - client.weaponWheel = true - Utils.WeaponWheel(true) + Utils.WeaponWheel(false) + end) - -- todo: check if current seat has weapon - -- local playerSeat + client.interval = SetInterval(function() + local playerPed = cache.ped - -- for i = -1, seats do - -- if GetPedInVehicleSeat(vehicle, i) == playerPed then - -- playerSeat = i - -- break - -- end - -- end - end - else - client.weaponWheel = false - Utils.WeaponWheel(false) - end - end + if invOpen == false then + playerCoords = GetEntityCoords(playerPed) if closestMarker[1] then table.wipe(closestMarker) end + local vehicle = cache.vehicle + Markers(drops, 'drop', vec3(150, 30, 30), nil, vehicle) if not shared.qtarget then @@ -908,7 +895,7 @@ RegisterNetEvent('ox_inventory:setPlayerInventory', function(currentDrops, inven Markers(Licenses, 'license', vec(30, 150, 30), nil, vehicle) - if currentWeapon and IsPedUsingActionMode(PlayerData.ped) then SetPedUsingActionMode(PlayerData.ped, false, -1, 'DEFAULT_ACTION') end + if currentWeapon and IsPedUsingActionMode(cache.ped) then SetPedUsingActionMode(cache.ped, false, -1, 'DEFAULT_ACTION') end elseif invOpen == true then if not CanOpenInventory() then @@ -946,8 +933,7 @@ RegisterNetEvent('ox_inventory:setPlayerInventory', function(currentDrops, inven local EnableKeys = client.enablekeys client.tick = SetInterval(function(disableControls) - local playerPed = PlayerData.ped - DisablePlayerVehicleRewards(PlayerData.id) + DisablePlayerVehicleRewards(cache.playerId) if invOpen then DisableAllControlActions(0) @@ -963,7 +949,7 @@ RegisterNetEvent('ox_inventory:setPlayerInventory', function(currentDrops, inven end else disableControls() - if invBusy then DisablePlayerFiring(PlayerData.id, true) end + if invBusy then DisablePlayerFiring(cache.playerId, true) end for _, v in pairs(nearbyMarkers) do local coords, rgb = v[1], v[2] @@ -986,7 +972,9 @@ RegisterNetEvent('ox_inventory:setPlayerInventory', function(currentDrops, inven if currentWeapon then DisableControlAction(0, 140, true) - if client.aimedfiring and not IsPlayerFreeAiming(PlayerData.id) then DisablePlayerFiring(PlayerData.id, true) end + if client.aimedfiring and not IsPlayerFreeAiming(cache.playerId) then DisablePlayerFiring(cache.playerId, true) end + + local playerPed = cache.ped if not invBusy and currentWeapon.timer ~= 0 and currentWeapon.timer < GetGameTimer() then currentWeapon.timer = 0 @@ -1090,8 +1078,8 @@ RegisterNUICallback('removeComponent', function(data, cb) if data.slot ~= currentWeapon.slot then return Utils.Notify({type = 'error', text = shared.locale('weapon_hand_wrong')}) end local itemSlot = PlayerData.inventory[currentWeapon.slot] for _, component in pairs(Items[data.component].client.component) do - if HasPedGotWeaponComponent(PlayerData.ped, currentWeapon.hash, component) then - RemoveWeaponComponentFromPed(PlayerData.ped, currentWeapon.hash, component) + if HasPedGotWeaponComponent(cache.ped, currentWeapon.hash, component) then + RemoveWeaponComponentFromPed(cache.ped, currentWeapon.hash, component) for k, v in pairs(itemSlot.metadata.components) do if v == data.component then table.remove(itemSlot.metadata.components, k) @@ -1113,21 +1101,11 @@ end) RegisterNUICallback('giveItem', function(data, cb) cb(1) - local vehicle = PlayerData.currentVehicle - - if vehicle then - local seats = GetVehicleMaxNumberOfPassengers(vehicle) - 1 + if cache.vehicle then + local seats = GetVehicleMaxNumberOfPassengers(cache.vehicle) - 1 if seats >= 0 then - local playerSeat - for i = -1, seats do - if GetPedInVehicleSeat(vehicle, i) == PlayerData.ped then - playerSeat = i - break - end - end - - local passenger = GetPedInVehicleSeat(playerSeat - 2 * (playerSeat % 2) + 1) + local passenger = GetPedInVehicleSeat(cache.seat - 2 * (cache.seat % 2) + 1) if passenger ~= 0 then passenger = GetPlayerServerId(NetworkGetPlayerIndexFromPed(passenger)) @@ -1138,7 +1116,7 @@ RegisterNUICallback('giveItem', function(data, cb) else local target = Utils.Raycast(12) - if target and IsPedAPlayer(target) and #(GetEntityCoords(PlayerData.ped, true) - GetEntityCoords(target, true)) < 2.3 then + if target and IsPedAPlayer(target) and #(GetEntityCoords(cache.ped, true) - GetEntityCoords(target, true)) < 2.3 then target = GetPlayerServerId(NetworkGetPlayerIndexFromPed(target)) Utils.PlayAnim(2000, 'mp_common', 'givetake1_a', 1.0, 1.0, -1, 50, 0.0, 0, 0, 0) TriggerServerEvent('ox_inventory:giveItem', data.slot, target, data.count) From 049eaeb9aa1d4db4b90d4b213b1fa483e842e15b Mon Sep 17 00:00:00 2001 From: Linden <65407488+thelindat@users.noreply.github.com> Date: Tue, 1 Mar 2022 16:08:03 +0000 Subject: [PATCH 08/10] feat(mysql): implement mysql module Moves most queries into a new module, to simplify configuration when using other frameworks. --- fxmanifest.lua | 1 + modules/bridge/server.lua | 12 +----- modules/inventory/server.lua | 45 ++++++---------------- modules/mysql/server.lua | 75 ++++++++++++++++++++++++++++++++++++ modules/shops/server.lua | 2 +- server.lua | 6 ++- 6 files changed, 94 insertions(+), 47 deletions(-) create mode 100644 modules/mysql/server.lua diff --git a/fxmanifest.lua b/fxmanifest.lua index cda5c58d62..ed6a7445d4 100644 --- a/fxmanifest.lua +++ b/fxmanifest.lua @@ -41,6 +41,7 @@ client_scripts { server_scripts { '@oxmysql/lib/MySQL.lua', + 'modules/mysql/server.lua', 'modules/logs/server.lua', 'modules/items/server.lua', 'modules/inventory/server.lua', diff --git a/modules/bridge/server.lua b/modules/bridge/server.lua index 0f5e03104d..89eb462a40 100644 --- a/modules/bridge/server.lua +++ b/modules/bridge/server.lua @@ -27,12 +27,7 @@ function server.setPlayerData(player) } end -if shared.framework == 'ox' then - function server.getInventory(identifier) - local inventory = MySQL.prepare.await('SELECT inventory FROM characters WHERE charid = ?', { identifier }) - return inventory and json.decode(inventory) - end -elseif shared.framework == 'esx' then +if shared.framework == 'esx' then local ESX = exports['es_extended']:getSharedObject() if ESX.CreatePickup then @@ -68,11 +63,6 @@ elseif shared.framework == 'esx' then } end - function server.getInventory(identifier) - local inventory = MySQL.prepare.await('SELECT inventory FROM users WHERE identifier = ?', { identifier }) - return inventory and json.decode(inventory) - end - RegisterServerEvent('ox_inventory:requestPlayerInventory', function() local source = source local player = server.GetPlayerFromId(source) diff --git a/modules/inventory/server.lua b/modules/inventory/server.lua index 562a9b1e16..53e1091583 100644 --- a/modules/inventory/server.lua +++ b/modules/inventory/server.lua @@ -209,16 +209,14 @@ function Inventory.Save(inv) local inventory = json.encode(minimal(inv)) if inv.type == 'player' then - MySQL.prepare('UPDATE users SET inventory = ? WHERE identifier = ?', { inventory, inv.owner }) + MySQL:savePlayer(inv.owner, inventory) else if inv.type == 'trunk' then - MySQL.prepare('UPDATE owned_vehicles SET trunk = ? WHERE plate = ?', { inventory, Inventory.GetPlateFromId(inv.id) }) + MySQL:saveTrunk(Inventory.GetPlateFromId(inv.id), inventory) elseif inv.type == 'glovebox' then - MySQL.prepare('UPDATE owned_vehicles SET glovebox = ? WHERE plate = ?', { inventory, Inventory.GetPlateFromId(inv.id) }) + MySQL:saveGlovebox(Inventory.GetPlateFromId(inv.id), inventory) else - MySQL.prepare('INSERT INTO ox_inventory (owner, name, data) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE data = VALUES(data)', { - inv.owner or '', inv.dbId, inventory, - }) + MySQL:saveStash(inv.owner, inv.dbId, inventory) end inv.changed = false end @@ -294,7 +292,7 @@ function Inventory.Load(id, invType, owner) datastore = true end elseif invType == 'trunk' or invType == 'glovebox' then - result = MySQL.prepare.await('SELECT plate, '..invType..' FROM owned_vehicles WHERE plate = ?', { Inventory.GetPlateFromId(id) }) + result = invType == 'trunk' and MySQL:loadTrunk( Inventory.GetPlateFromId(id) ) or MySQL:loadGlovebox( Inventory.GetPlateFromId(id) ) if not result then if server.randomloot then @@ -304,7 +302,7 @@ function Inventory.Load(id, invType, owner) end else result = result[invType] end else - result = MySQL.prepare.await('SELECT data FROM ox_inventory WHERE owner = ? AND name = ?', { owner or '', id }) + result = MySQL:loadStash(owner or '', id) end end @@ -760,19 +758,11 @@ exports('CustomDrop', CustomDrop) function Inventory.Confiscate(source) local inv = Inventories[source] if inv?.player then - local inventory = json.encode(minimal(inv)) - MySQL.update('INSERT INTO ox_inventory (owner, name, data) VALUES (:owner, :name, :data) ON DUPLICATE KEY UPDATE data = :data', { - owner = inv.owner, - name = inv.owner, - data = inventory, - }, function (result) - if result > 0 then - table.wipe(inv.items) - inv.weight = 0 - TriggerClientEvent('ox_inventory:inventoryConfiscated', inv.id) - if shared.framework == 'esx' then Inventory.SyncInventory(inv) end - end - end) + MySQL:saveStash(inv.owner, inv.owner, json.encode(minimal(inv))) + table.wipe(inv.items) + inv.weight = 0 + TriggerClientEvent('ox_inventory:inventoryConfiscated', inv.id) + if shared.framework == 'esx' then Inventory.SyncInventory(inv) end end end exports('ConfiscateInventory', Inventory.Confiscate) @@ -894,18 +884,7 @@ SetInterval(function() end end - if #parameters[1] > 0 then - MySQL.prepare.await('UPDATE owned_vehicles SET trunk = ? WHERE plate = ?', parameters[1]) - end - - if #parameters[2] > 0 then - MySQL.prepare.await('UPDATE owned_vehicles SET glovebox = ? WHERE plate = ?', parameters[2]) - end - - if #parameters[3] > 0 then - MySQL.prepare.await('INSERT INTO ox_inventory (owner, name, data) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE data = VALUES(data)', parameters[3]) - end - + MySQL:saveInventories(parameters[1], parameters[2], parameters[3]) end, 600000) local function saveInventories() diff --git a/modules/mysql/server.lua b/modules/mysql/server.lua new file mode 100644 index 0000000000..7e13881e73 --- /dev/null +++ b/modules/mysql/server.lua @@ -0,0 +1,75 @@ +local Query = { + SELECT_STASH = 'SELECT data FROM ox_inventory WHERE owner = ? AND name = ?', + UPDATE_STASH = 'INSERT INTO ox_inventory (owner, name, data) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE data = VALUES(data)', + SELECT_GLOVEBOX = 'SELECT plate, glovebox FROM `vehicles` WHERE plate = ?', + SELECT_TRUNK = 'SELECT plate, trunk FROM `vehicles` WHERE plate = ?', + SELECT_PLAYER = 'SELECT inventory FROM `characters` WHERE charid = ?', + UPDATE_TRUNK = 'UPDATE `vehicles` SET trunk = ? WHERE plate = ?', + UPDATE_GLOVEBOX = 'UPDATE `vehicles` SET glovebox = ? WHERE plate = ?', + UPDATE_PLAYER = 'UPDATE `characters` SET inventory = ? WHERE identifier = ?', +} + +local function replace(playerColumn, vehicleColumn) + for k, v in pairs(Query) do + if v:find('vehicles') then + Query[k] = v:gsub('vehicles', vehicleColumn) + elseif v:find('characters') then + Query[k] = v:gsub('characters', playerColumn) + end + end +end + +if shared.framework == 'esx' then + replace('users', 'owned_vehicles') +end + +function MySQL:loadPlayer(identifier) + local inventory = self.prepare.await(Query.SELECT_PLAYER, { identifier }) + return inventory and json.decode(inventory) +end + +function MySQL:savePlayer(owner, inventory) + return self.prepare(Query.UPDATE_PLAYER, { inventory, owner }) +end + +function MySQL:saveStash(owner, dbId, inventory) + return self.prepare(Query.UPDATE_STASH, { owner or '', dbId, inventory }) +end + +function MySQL:loadStash(owner, name) + return self.prepare.await(Query.SELECT_STASH, { owner or '', name }) +end + +function MySQL:saveGlovebox(plate, inventory) + return self.prepare(Query.UPDATE_GLOVEBOX, { inventory, plate }) +end + +function MySQL:loadGlovebox(plate) + return self.prepare.await(Query.SELECT_GLOVEBOX, { plate }) +end + +function MySQL:saveTrunk(plate, inventory) + return self.prepare(Query.UPDATE_TRUNK, { inventory, plate }) +end + +function MySQL:loadTrunk(plate) + return self.prepare.await(Query.SELECT_TRUNK, { plate }) +end + +function MySQL:saveInventories(trunks, gloveboxes, stashes) + if #trunks > 0 then + MySQL.prepare.await(Query.UPDATE_TRUNK, trunks) + end + + if #gloveboxes > 0 then + MySQL.prepare.await(Query.UPDATE_GLOVEBOX, gloveboxes) + end + + if #stashes > 0 then + MySQL.prepare.await(Query.UPDATE_STASH, stashes) + end +end + +function MySQL:selectLicense(name, owner) + return MySQL.scalar.await('SELECT 1 FROM user_licenses WHERE type = ? AND owner = ?', { name, owner }) +end diff --git a/modules/shops/server.lua b/modules/shops/server.lua index 415c754bdd..5217a0a636 100644 --- a/modules/shops/server.lua +++ b/modules/shops/server.lua @@ -114,7 +114,7 @@ lib.callback.register('ox_inventory:buyItem', function(source, data) data.count = fromData.count end - elseif fromData.license and not MySQL.scalar.await('SELECT 1 FROM user_licenses WHERE type = ? AND owner = ?', { fromData.license, playerInv.owner }) then + elseif fromData.license and shared.framework == 'esx' and not MySQL:selectLicense(fromData.license, playerInv.owner) then return false, false, {type = 'error', text = shared.locale('item_unlicensed')} elseif fromData.grade then diff --git a/server.lua b/server.lua index 74f3925431..1694cebddb 100644 --- a/server.lua +++ b/server.lua @@ -11,7 +11,7 @@ local function setPlayerInventory(player, data) while not shared.ready do Wait(0) end if not data then - data = server.getInventory(player.identifier) + data = MySQL:loadPlayer(player.identifier) end local inventory = {} @@ -427,7 +427,8 @@ lib.callback.register('ox_inventory:buyLicense', function(source, id) local license = Licenses[id] if license then local inventory = Inventory(source) - local result = MySQL.scalar.await('SELECT 1 FROM user_licenses WHERE type = ? AND owner = ?', { license.name, inventory.owner }) + local result = MySQL:selectLicense(license.name, inventory.owner) + if result then return false, 'has_weapon_license' elseif Inventory.GetItem(inventory, 'money', false, true) < license.price then @@ -435,6 +436,7 @@ lib.callback.register('ox_inventory:buyLicense', function(source, id) else Inventory.RemoveItem(inventory, 'money', license.price) TriggerEvent('esx_license:addLicense', source, 'weapon') + return true, 'bought_weapon_license' end end From 1e15efce74d092fa2e9e5fb4964b1f97dd080a46 Mon Sep 17 00:00:00 2001 From: Linden <65407488+thelindat@users.noreply.github.com> Date: Wed, 2 Mar 2022 02:28:57 +0000 Subject: [PATCH 09/10] refactor(client): change PlayerData.ped to cache.ped --- client.lua | 40 ++++++++++++++++---------------- modules/interface/client.lua | 12 +++++----- modules/items/client.lua | 16 ++++++------- modules/mysql/server.lua | 8 +++---- modules/utils/client.lua | 44 ++++++++++++++++++------------------ 5 files changed, 60 insertions(+), 60 deletions(-) diff --git a/client.lua b/client.lua index 576e6e8e01..f48018ee26 100644 --- a/client.lua +++ b/client.lua @@ -219,7 +219,7 @@ local function useSlot(slot) return data.client.export(0, data, {name = item.name, slot = item.slot, metadata = item.metadata}) elseif data.client.event then -- deprecated, to be removed - return print(('unable to trigger event for %s, data.client.event has been removed. utilise exports instead.'):format(item.name)) + return error(('unable to trigger event for %s, data.client.event has been removed. utilise exports instead.'):format(item.name)) end end @@ -770,6 +770,21 @@ local function setStateBagHandler(id) setStateBagHandler = nil end +lib.onCache('ped', function() + Utils.WeaponWheel(client.weaponWheel) +end) + +lib.onCache('vehicle', function(vehicle) + if vehicle then + if DoesVehicleHaveWeapons(vehicle) then + return Utils.WeaponWheel(true) + -- todo: check if current seat has weapon + end + end + + Utils.WeaponWheel(false) +end) + RegisterNetEvent('ox_inventory:setPlayerInventory', function(currentDrops, inventory, weight, esxItem, player, source) PlayerData = player PlayerData.id = cache.playerId @@ -778,8 +793,8 @@ RegisterNetEvent('ox_inventory:setPlayerInventory', function(currentDrops, inven setmetatable(PlayerData, { __index = function(self, key) if key == 'ped' then - return cache.ped - else return false end + return PlayerPedId() + end end }) @@ -798,7 +813,6 @@ RegisterNetEvent('ox_inventory:setPlayerInventory', function(currentDrops, inven currentWeapon = nil drops = currentDrops Utils.ClearWeapons() - Utils.WeaponWheel(false) local ItemData = table.create(0, #Items) @@ -846,24 +860,10 @@ RegisterNetEvent('ox_inventory:setPlayerInventory', function(currentDrops, inven plyState:set('invBusy', false, false) plyState:set('invOpen', false, false) TriggerEvent('ox_inventory:updateInventory', PlayerData.inventory) - Utils.Notify({text = shared.locale('inventory_setup'), duration = 2500}) - local Licenses = data 'licenses' - - lib.onCache('ped', function() - Utils.WeaponWheel(client.weaponWheel) - end) - - lib.onCache('vehicle', function(vehicle) - if vehicle then - if DoesVehicleHaveWeapons(vehicle) then - return Utils.WeaponWheel(true) - -- todo: check if current seat has weapon - end - end + Utils.WeaponWheel(false) - Utils.WeaponWheel(false) - end) + local Licenses = data 'licenses' client.interval = SetInterval(function() local playerPed = cache.ped diff --git a/modules/interface/client.lua b/modules/interface/client.lua index 714894efdc..18e69b525e 100644 --- a/modules/interface/client.lua +++ b/modules/interface/client.lua @@ -44,7 +44,7 @@ Interface.ProgressActive = false local function ResetPlayer() if progress.anim or progress.scenario then - ClearPedTasks(PlayerData.ped) + ClearPedTasks(cache.ped) end for i = 1, 2 do @@ -79,7 +79,7 @@ local Animations = data 'animations' function Interface.Progress(options, completed) if Interface.ProgressActive == false then progress.callback = completed - if not IsEntityDead(PlayerData.ped) or options.useWhileDead then + if not IsEntityDead(cache.ped) or options.useWhileDead then if options.disable then local count = 0 for key, disable in pairs(options.disable) do @@ -110,12 +110,12 @@ function Interface.Progress(options, completed) if options.anim then if options.anim.dict then lib.requestAnimDict(options.anim.dict) - TaskPlayAnim(PlayerData.ped, options.anim.dict, options.anim.clip, 3.0, 1.0, -1, options.anim.flag or 49, 0, false, false, false) + TaskPlayAnim(cache.ped, options.anim.dict, options.anim.clip, 3.0, 1.0, -1, options.anim.flag or 49, 0, false, false, false) progress.anim = true end if options.anim.scenario and not options.anim.dict then - TaskStartScenarioInPlace(PlayerData.ped, options.anim.scenario, 0, true) + TaskStartScenarioInPlace(cache.ped, options.anim.scenario, 0, true) progress.scenario = true end end @@ -130,7 +130,7 @@ function Interface.Progress(options, completed) lib.requestModel(model) - local pCoords = GetOffsetFromEntityInWorldCoords(PlayerData.ped, 0.0, 0.0, 0.0) + local pCoords = GetOffsetFromEntityInWorldCoords(cache.ped, 0.0, 0.0, 0.0) local modelSpawn = CreateObject(model, pCoords.x, pCoords.y, pCoords.z, true, true, true) local netid = ObjToNet(modelSpawn) @@ -138,7 +138,7 @@ function Interface.Progress(options, completed) NetworkSetNetworkIdDynamic(netid, true) SetNetworkIdCanMigrate(netid, false) - AttachEntityToEntity(modelSpawn, PlayerData.ped, GetPedBoneIndex(PlayerData.ped, prop.bone or 60309), prop.pos.x or 0.0, prop.pos.y or 0.0, prop.pos.z or 0.0, prop.rot.x or 0.0, prop.rot.y or 0.0, prop.rot.z or 0.0, 1, 1, 0, 1, 0, 1) + AttachEntityToEntity(modelSpawn, cache.ped, GetPedBoneIndex(cache.ped, prop.bone or 60309), prop.pos.x or 0.0, prop.pos.y or 0.0, prop.pos.z or 0.0, prop.rot.x or 0.0, prop.rot.y or 0.0, prop.rot.z or 0.0, 1, 1, 0, 1, 0, 1) progress['prop'..i] = netid SetModelAsNoLongerNeeded(model) end diff --git a/modules/items/client.lua b/modules/items/client.lua index 11a9353dee..de4e973406 100644 --- a/modules/items/client.lua +++ b/modules/items/client.lua @@ -24,22 +24,22 @@ local ox_inventory = exports[shared.resource] ----------------------------------------------------------------------------------------------- Item('bandage', function(data, slot) - local maxHealth = GetEntityMaxHealth(PlayerData.ped) - local health = GetEntityHealth(PlayerData.ped) + local maxHealth = GetEntityMaxHealth(cache.ped) + local health = GetEntityHealth(cache.ped) ox_inventory:useItem(data, function(data) if data then - SetEntityHealth(PlayerData.ped, math.min(maxHealth, math.floor(health + maxHealth / 16))) + SetEntityHealth(cache.ped, math.min(maxHealth, math.floor(health + maxHealth / 16))) ox_inventory:notify({text = 'You feel better already'}) end end) end) Item('armour', function(data, slot) - if GetPedArmour(PlayerData.ped) < 100 then + if GetPedArmour(cache.ped) < 100 then ox_inventory:useItem(data, function(data) if data then SetPlayerMaxArmour(PlayerData.id, 100) - SetPedArmour(PlayerData.ped, 100) + SetPedArmour(cache.ped, 100) end end) end @@ -52,10 +52,10 @@ Item('parachute', function(data, slot) if data then local chute = `GADGET_PARACHUTE` SetPlayerParachuteTintIndex(PlayerData.id, -1) - GiveWeaponToPed(PlayerData.ped, chute, 0, true, false) - SetPedGadget(PlayerData.ped, chute, true) + GiveWeaponToPed(cache.ped, chute, 0, true, false) + SetPedGadget(cache.ped, chute, true) lib.requestModel(1269906701) - client.parachute = CreateParachuteBagObject(PlayerData.ped, true, true) + client.parachute = CreateParachuteBagObject(cache.ped, true, true) if slot.metadata.type then SetPlayerParachuteTintIndex(PlayerData.id, slot.metadata.type) end diff --git a/modules/mysql/server.lua b/modules/mysql/server.lua index 7e13881e73..ce2450c86a 100644 --- a/modules/mysql/server.lua +++ b/modules/mysql/server.lua @@ -58,18 +58,18 @@ end function MySQL:saveInventories(trunks, gloveboxes, stashes) if #trunks > 0 then - MySQL.prepare.await(Query.UPDATE_TRUNK, trunks) + self.prepare.await(Query.UPDATE_TRUNK, trunks) end if #gloveboxes > 0 then - MySQL.prepare.await(Query.UPDATE_GLOVEBOX, gloveboxes) + self.prepare.await(Query.UPDATE_GLOVEBOX, gloveboxes) end if #stashes > 0 then - MySQL.prepare.await(Query.UPDATE_STASH, stashes) + self.prepare.await(Query.UPDATE_STASH, stashes) end end function MySQL:selectLicense(name, owner) - return MySQL.scalar.await('SELECT 1 FROM user_licenses WHERE type = ? AND owner = ?', { name, owner }) + return self.scalar.await('SELECT 1 FROM user_licenses WHERE type = ? AND owner = ?', { name, owner }) end diff --git a/modules/utils/client.lua b/modules/utils/client.lua index a80962195e..9f1f909a7a 100644 --- a/modules/utils/client.lua +++ b/modules/utils/client.lua @@ -3,25 +3,25 @@ local Utils = {} function Utils.PlayAnim(wait, dict, name, blendIn, blendOut, duration, flag, rate, lockX, lockY, lockZ) lib.requestAnimDict(dict) CreateThread(function() - TaskPlayAnim(PlayerData.ped, dict, name, blendIn, blendOut, duration, flag, rate, lockX, lockY, lockZ) + TaskPlayAnim(cache.ped, dict, name, blendIn, blendOut, duration, flag, rate, lockX, lockY, lockZ) Wait(wait) - if wait > 0 then ClearPedSecondaryTask(PlayerData.ped) end + if wait > 0 then ClearPedSecondaryTask(cache.ped) end end) end function Utils.PlayAnimAdvanced(wait, dict, name, posX, posY, posZ, rotX, rotY, rotZ, animEnter, animExit, duration, flag, time) lib.requestAnimDict(dict) CreateThread(function() - TaskPlayAnimAdvanced(PlayerData.ped, dict, name, posX, posY, posZ, rotX, rotY, rotZ, animEnter, animExit, duration, flag, time, 0, 0) + TaskPlayAnimAdvanced(cache.ped, dict, name, posX, posY, posZ, rotX, rotY, rotZ, animEnter, animExit, duration, flag, time, 0, 0) Wait(wait) - if wait > 0 then ClearPedSecondaryTask(PlayerData.ped) end + if wait > 0 then ClearPedSecondaryTask(cache.ped) end end) end function Utils.Raycast(flag) - local playerCoords = GetEntityCoords(PlayerData.ped) - local plyOffset = GetOffsetFromEntityInWorldCoords(PlayerData.ped, 0.0, 2.2, -0.05) - local rayHandle = StartShapeTestCapsule(playerCoords.x, playerCoords.y, playerCoords.z, plyOffset.x, plyOffset.y, plyOffset.z, 2.2, flag or 30, PlayerData.ped) + local playerCoords = GetEntityCoords(cache.ped) + local plyOffset = GetOffsetFromEntityInWorldCoords(cache.ped, 0.0, 2.2, -0.05) + local rayHandle = StartShapeTestCapsule(playerCoords.x, playerCoords.y, playerCoords.z, plyOffset.x, plyOffset.y, plyOffset.z, 2.2, flag or 30, cache.ped) while true do Wait(0) local result, _, _, _, entityHit = GetShapeTestResult(rayHandle) @@ -37,7 +37,7 @@ function Utils.Raycast(flag) end function Utils.GetClosestPlayer() - local closestPlayer, playerId, playerCoords = vec3(10, 0, 0), PlayerId(), GetEntityCoords(PlayerData.ped) + local closestPlayer, playerId, playerCoords = vec3(10, 0, 0), PlayerId(), GetEntityCoords(cache.ped) local coords for k, player in pairs(GetActivePlayers()) do if player ~= playerId then @@ -60,28 +60,28 @@ exports('notify', Utils.Notify) function Utils.Disarm(currentWeapon, newSlot) SetWeaponsNoAutoswap(1) SetWeaponsNoAutoreload(1) - SetPedCanSwitchWeapon(PlayerData.ped, 0) - SetPedEnableWeaponBlocking(PlayerData.ped, 1) + SetPedCanSwitchWeapon(cache.ped, 0) + SetPedEnableWeaponBlocking(cache.ped, 1) if currentWeapon then - local ammo = currentWeapon.ammo and GetAmmoInPedWeapon(PlayerData.ped, currentWeapon.hash) - SetPedAmmo(PlayerData.ped, currentWeapon.hash, 0) + local ammo = currentWeapon.ammo and GetAmmoInPedWeapon(cache.ped, currentWeapon.hash) + SetPedAmmo(cache.ped, currentWeapon.hash, 0) if not newSlot then - ClearPedSecondaryTask(PlayerData.ped) + ClearPedSecondaryTask(cache.ped) local sleep = (client.hasGroup(shared.police) and (GetWeapontypeGroup(currentWeapon.hash) == 416676503 or GetWeapontypeGroup(currentWeapon.hash) == 690389602)) and 450 or 1400 - local coords = GetEntityCoords(PlayerData.ped, true) + local coords = GetEntityCoords(cache.ped, true) if currentWeapon.name == 'WEAPON_SWITCHBLADE' then - Utils.PlayAnimAdvanced(sleep, 'anim@melee@switchblade@holster', 'holster', coords.x, coords.y, coords.z, 0, 0, GetEntityHeading(PlayerData.ped), 8.0, 3.0, -1, 48, 0) + Utils.PlayAnimAdvanced(sleep, 'anim@melee@switchblade@holster', 'holster', coords.x, coords.y, coords.z, 0, 0, GetEntityHeading(cache.ped), 8.0, 3.0, -1, 48, 0) Wait(600) else - Utils.PlayAnimAdvanced(sleep, (sleep == 450 and 'reaction@intimidation@cop@unarmed' or 'reaction@intimidation@1h'), 'outro', coords.x, coords.y, coords.z, 0, 0, GetEntityHeading(PlayerData.ped), 8.0, 3.0, -1, 50, 0) + Utils.PlayAnimAdvanced(sleep, (sleep == 450 and 'reaction@intimidation@cop@unarmed' or 'reaction@intimidation@1h'), 'outro', coords.x, coords.y, coords.z, 0, 0, GetEntityHeading(cache.ped), 8.0, 3.0, -1, 50, 0) Wait(sleep) end Utils.ItemNotify({currentWeapon.label, currentWeapon.name, shared.locale('holstered')}) end - RemoveAllPedWeapons(PlayerData.ped, true) + RemoveAllPedWeapons(cache.ped, true) if newSlot then TriggerServerEvent('ox_inventory:updateWeapon', ammo and 'ammo' or 'melee', ammo or currentWeapon.melee, newSlot) @@ -94,11 +94,11 @@ end function Utils.ClearWeapons(currentWeapon) currentWeapon = Utils.Disarm(currentWeapon) - RemoveAllPedWeapons(PlayerData.ped, true) + RemoveAllPedWeapons(cache.ped, true) if client.parachute then local chute = `GADGET_PARACHUTE` - GiveWeaponToPed(PlayerData.ped, chute, 0, true, false) - SetPedGadget(PlayerData.ped, chute, true) + GiveWeaponToPed(cache.ped, chute, 0, true, false) + SetPedGadget(cache.ped, chute, true) end end @@ -113,8 +113,8 @@ function Utils.WeaponWheel(state) client.weaponWheel = state SetWeaponsNoAutoswap(not state) SetWeaponsNoAutoreload(not state) - SetPedCanSwitchWeapon(PlayerData.ped, state) - SetPedEnableWeaponBlocking(PlayerData.ped, not state) + SetPedCanSwitchWeapon(cache.ped, state) + SetPedEnableWeaponBlocking(cache.ped, not state) end exports('weaponWheel', Utils.WeaponWheel) From 6a67dc0b3f786de2e3350eaa6a6f432410605b3e Mon Sep 17 00:00:00 2001 From: Linden <65407488+thelindat@users.noreply.github.com> Date: Wed, 2 Mar 2022 17:45:13 +1100 Subject: [PATCH 10/10] refactor: remove limit system This shit barely functions and is not worth the hours it will take to make it work. --- data/items.lua | 1 - modules/inventory/server.lua | 7 +------ modules/shops/server.lua | 5 ----- server.lua | 21 --------------------- 4 files changed, 1 insertion(+), 33 deletions(-) diff --git a/data/items.lua b/data/items.lua index d53f644d0b..467b37890e 100644 --- a/data/items.lua +++ b/data/items.lua @@ -3,7 +3,6 @@ return { label = 'Test Burger', weight = 220, degrade = 60, - limit = 3, client = { status = { hunger = 200000 }, anim = 'eating', diff --git a/modules/inventory/server.lua b/modules/inventory/server.lua index 53e1091583..b2fcdfc7e7 100644 --- a/modules/inventory/server.lua +++ b/modules/inventory/server.lua @@ -584,7 +584,7 @@ function Inventory.GetItemSlots(inv, item, metadata) if metadata and v.metadata == nil then v.metadata = {} end - if not metadata or item.limit or table.matches(v.metadata, metadata) then + if not metadata or table.matches(v.metadata, metadata) then totalCount = totalCount + v.count slots[k] = v.count end @@ -668,11 +668,6 @@ function Inventory.CanCarryItem(inv, item, count, metadata) local itemSlots, totalCount, emptySlots = Inventory.GetItemSlots(inv, item, metadata == nil and {} or type(metadata) == 'string' and {type=metadata} or metadata) if next(itemSlots) or emptySlots > 0 then - if inv.type == 'player' and item.limit and (totalCount + count) > item.limit then - TriggerClientEvent('ox_inventory:notify', inv.id, {type = 'error', text = shared.locale('cannot_carry_limit', item.limit, item.label)}) - return false - end - if item.weight == 0 then return true end if count == nil then count = 1 end local newWeight = inv.weight + (item.weight * count) diff --git a/modules/shops/server.lua b/modules/shops/server.lua index 5217a0a636..f49694fdfd 100644 --- a/modules/shops/server.lua +++ b/modules/shops/server.lua @@ -134,11 +134,6 @@ lib.callback.register('ox_inventory:buyItem', function(source, data) local metadata, count = Items.Metadata(playerInv, fromItem, fromData.metadata and table.clone(fromData.metadata) or {}, data.count) local price = count * fromData.price - local _, totalCount, _ = Inventory.GetItemSlots(playerInv, fromItem, fromItem.metadata) - if fromItem.limit and (totalCount + data.count) > fromItem.limit then - return false, false, {type = 'error', text = shared.locale('cannot_carry_limit', fromItem.limit, fromItem.label)} - end - if toData == nil or (fromItem.name == toItem.name and fromItem.stack and table.matches(toData.metadata, metadata)) then local canAfford = Inventory.GetItem(source, currency, false, true) >= price if canAfford then diff --git a/server.lua b/server.lua index 1694cebddb..042c51f198 100644 --- a/server.lua +++ b/server.lua @@ -203,27 +203,6 @@ lib.callback.register('ox_inventory:swapItems', function(source, data) fromInventory = (data.fromType == 'player' and playerInventory) or Inventory(playerInventory.open) end - if not sameInventory and toInventory.type == 'player' or toInventory.type == 'otherplayer' then - local fromData = fromInventory.items[data.fromSlot] - - if not fromData then - TriggerClientEvent('ox_inventory:closeInventory', source, true) - return - end - - local fromItem = Items(fromData.name) - local _, totalCount, _ = Inventory.GetItemSlots(toInventory, fromItem, fromItem.metadata) - - if fromItem.limit and (totalCount + data.count) > fromItem.limit then - if toInventory.type == 'player' then - TriggerClientEvent('ox_inventory:notify', source, {type = 'error', text = shared.locale('cannot_carry_limit', fromItem.limit, fromItem.label)}) - elseif toInventory.type == 'otherplayer' then - TriggerClientEvent('ox_inventory:notify', source, {type = 'error', text = shared.locale('cannot_carry_limit_other', fromItem.limit, fromItem.label)}) - end - return - end - end - if fromInventory.type == 'policeevidence' and not sameInventory then local group, rank = server.hasGroup(toInventory, shared.police)