Merge pull request #156 from TheOrderFivem/dev

Release v0.12.0 - Major Framework Enhancements and Entity System Overhaul
This commit is contained in:
MrNewb authored and GitHub committed 2025-09-10 13:46:59 -04:00
commit bc3558c622
204 files changed
+4563 -2704

No files matched your search

+69 -66
View File
@@ -1,119 +1,122 @@
# Attributions
> **Community Bridge** This project incorporates code from several outstanding libraries and resources, all licensed under GPLv3. We're grateful to the talented developers who made their work available to the community.
> **Community Bridge** incorporates code from several outstanding libraries and resources, all licensed under GPLv3. We’re grateful to the talented developers who made their work available to the community.
---
## Libraries & Resources
### r\_bridge
**Purpose:** Code for codem-inventory bridging, and initial targeting
**Repository:** [r\_bridge](https://github.com/rumaier/r_bridge)
<details>
<summary>Implementation Details</summary>
<summary><strong>r_bridge</strong></summary>
**Purpose:** Code for codem-inventory bridging, and initial targeting
**Repository:** [r_bridge](https://github.com/rumaier/r_bridge)
**Code we use:**
* Inventory bridging code for codem-inventory integration
* Targeting system foundation
- Inventory bridging code for codem-inventory integration
- Targeting system foundation
**Modifications made:**
* Adapted inventory bridge for codem compatibility in alternative structure
- Adapted inventory bridge for codem compatibility in alternative structure
</details>
---
### dirk\_lib
**Purpose:** Vehicle fuel and vehicle key bridging systems
**Repository:** [dirk\_lib](https://github.com/DirkDigglerz/dirk_lib)
<details>
<summary>Implementation Details</summary>
<summary><strong>ox_lib</strong></summary>
**Code we use:**
* Client-side vehicle fuel management
* Vehicle key bridging functionality
**Modifications made:**
* None - code used as-is with full credit to original author
</details>
---
### ox\_lib
**Purpose:** External compatibility and architectural inspiration
**Repository:** [ox\_lib](https://github.com/overextended/ox_lib)
<details>
<summary>Implementation Details</summary>
**Purpose:** Architectural inspiration
**Repository:** [ox_lib](https://github.com/overextended/ox_lib)
**Compatibility features:**
* External resource integration for raycasting utilities
* Shared conventions
- External resource integration for raycasting utilities
- Shared conventions
**Implementation approach:**
* No direct code usage - maintains compatibility as external resource
* Follows ox\_lib conventions for seamless integration
* Provides bridge compatibility for servers using ox\_lib ecosystem
- No direct code usage — maintains compatibility as external resource
- Follows ox_lib conventions for seamless integration
- Provides bridge compatibility for servers using ox_lib ecosystem
</details>
---
### renewed\_lib
**Purpose:** Object placer functionality
**Repository:** [renewed\_lib](https://github.com/Renewed-Scripts/Renewed-Lib)
<details>
<summary>Implementation Details</summary>
<summary><strong>renewed_lib</strong></summary>
**Purpose:** Object placer functionality
**Repository:** [renewed_lib](https://github.com/Renewed-Scripts/Renewed-Lib)
**Code we use:**
* Object placement system
- Object placement system
**Modifications made:**
* Updated variable naming for consistency
* Added missing parameters for native functions
* Updated deprecated ox\_lib raycast camera export
* Enhanced showtext UI to work with multiple systems
* Moved placement text to locales for internationalization
* Replaced ox\_lib model request exports with our bridge functions
- Updated variable naming for consistency
- Added missing parameters for native functions
- Updated deprecated ox_lib raycast camera export
- Enhanced showtext UI to work with multiple systems
- Moved placement text to locales for internationalization
- Replaced ox_lib model request exports with our bridge functions
</details>
---
### duff
<details>
<summary><strong>duff</strong></summary>
**Purpose:** Version checker system and update notifications
**Purpose:** Version checker system and update notifications
**Repository:** [duff](https://github.com/DonHulieo/duff/blob/d89ed3b0051194babf5711114a0c437d4e41f433/server/init.lua#L10C1-L28C4)
<details>
<summary>Implementation Details</summary>
**Code we use:**
* Version checker formatting patterns
* Repository information handling
- Version checker formatting patterns
- Repository information handling
**Modifications made:**
* Removed unnecessary variables
* Enhanced to pull repository information from passed strings
* Adapted print formatting for our use case
- Removed unnecessary variables
- Enhanced to pull repository information from passed strings
- Adapted print formatting for our use case
</details>
---
<details>
<summary><strong>Vehicle Properties System</strong></summary>
**Purpose:** Set and manage vehicle properties in the game world, inspired by multiple community frameworks.
**Repositories referenced:**
- [ESX-Framework (ESX.Game.SetVehicleProperties)](https://github.com/esx-framework/es_extended)
- [QB-Core (qb-core)](https://github.com/qbcore-framework/qb-core)
- [ox_lib](https://github.com/overextended/ox_lib) (architectural inspiration and modifications)
**Code origin and inspiration:**
- Primarily draws on concepts and structures from ESX and QB-Core, with ox_lib serving as architectural inspiration.
- ESX and QB-Core implementations use similar approaches for setting vehicle mods, colors, damages, and extras.
- ox_lib adapts and extends these approaches within its framework, showing overlapping code patterns.
**Modifications made:**
- Combined and refactored logic to suit Community Bridge project needs.
- Adapted license to GPLv3 for compatibility and open-source compliance.
- Added explicit handling of custom colors, mod toggles, and damage states.
**Licensing notes:**
- Original ESX and QB-Core frameworks are GPLv3 licensed.
- ox_lib is LGPL licensed, used here as architectural inspiration only.
- This project’s vehicle properties code inherits GPLv3 licensing consistent with ESX/QB-Core, honoring their licensing terms and attributions.
</details>
@@ -121,7 +124,7 @@
## Special Thanks
A heartfelt thank you to all the creators and maintainers of these libraries, bridges, and resources. Your dedication to open-source development and the FiveM community makes projects like Community Bridge possible.
A heartfelt thank you to all creators and maintainers of these libraries, bridges, and resources. Your dedication to open-source development and the FiveM community makes projects like Community Bridge possible.
Your willingness to share knowledge and code under GPLv3 licensing enables the entire community to build better, more compatible systems together.
@@ -135,4 +138,4 @@ For detailed license information, see the [LICENSE](LICENSE) file in the project
---
> *"If I have seen further it is by standing on the shoulders of Giants."* - Isaac Newton
> *"If I have seen further it is by standing on the shoulders of Giants."* – Isaac Newton
+1 -2
View File
@@ -56,8 +56,7 @@ By bridging core game systems including inventory, dispatch, targeting, door loc
## Documentation
Complete developer documentation is available at:
[Community Bridge Documentation](https://mrnewbs-scrips.gitbook.io/the-order-of-the-sacred-framework)
[Community Bridge Documentation](https://theorderfivem.github.io/public_docs/)
---
## Community and Support
+20
View File
@@ -0,0 +1,20 @@
-- -- Make sure to include filename in the init (prefix of the .lua)Utility = Utility or Require("lib/utility/client/utility.lua")
-- local ParticlesBehaviors = {
-- tag = "isTemplate",
-- default = {
-- }
-- }
-- function ParticlesBehaviors.OnSpawn(entityData)
-- end
-- function ParticlesBehaviors.OnRemove(entityData)
-- end
-- function ParticlesBehaviors.OnUpdate(entityData)
-- end
-- return ParticlesBehaviors
+367
View File
@@ -0,0 +1,367 @@
Bridge = Bridge or exports['community_bridge']:Bridge()
-- RegisterCommand("ClientEntityParticles", function()
-- local position = GetEntityCoords(PlayerPedId())
-- local data = Bridge.ClientEntity.Create({
-- id = "particle_" .. math.random(1, 10000),
-- model = "mp_m_freemode_01",
-- coords = position,
-- entityType = "ped",
-- freeze = false,
-- follow = {
-- target = 1,
-- },
-- weapon = {
-- name = "WEAPON_PISTOL",
-- ammo = 100
-- },
-- stash = {
-- -- id = "generate from server",
-- label = "Test Stash",
-- target = {
-- label = "Open Stash",
-- description = "Access the stash to store or retrieve items.",
-- icon = "fas fa-boxes"
-- }
-- },
-- attach = {
-- target = 1,
-- bone = 57005, -- right hand
-- },
-- scenarios = {
-- name = "WORLD_HUMAN_CLIPBOARD",
-- introClip = true,
-- duration = 20000
-- },
-- anim = {
-- dict = "anim@mp_player_intcelebrationmale@wave",
-- name = "wave",
-- flags = 49,
-- duration = -1,
-- onComplete = function(entityData)
-- Bridge.ClientEntity.Set(entityData.id, "anim", {
-- dict = "rcmnigel1c",
-- name = "hailing_whistle_waive_a",
-- flags = entityData.anim.flags,
-- duration = 10000,
-- onComplete = function(entityData)
-- Bridge.ClientEntity.Set(entityData.id, "anim", {
-- dict = "timetable@denice@ig_1",
-- name = "idle_b",
-- flags = entityData.anim.flags,
-- duration = 10000,
-- onComplete = function(entityData)
-- print("hello")
-- end
-- })
-- end
-- })
-- end
-- },
-- clothing = {
-- components = {
-- { drawable = 0, texture = 0, component_id = 0 },
-- { drawable = 0, texture = 0, component_id = 1 },
-- { drawable = 19, texture = 0, component_id = 2 },
-- { drawable = 6, texture = 0, component_id = 3 },
-- { drawable = 0, texture = 0, component_id = 4 },
-- { drawable = 0, texture = 0, component_id = 5 },
-- { drawable = 0, texture = 0, component_id = 6 },
-- { drawable = 0, texture = 0, component_id = 7 },
-- { drawable = 23, texture = 0, component_id = 8 },
-- { drawable = 0, texture = 0, component_id = 9 },
-- { drawable = 0, texture = 0, component_id = 10 },
-- { drawable = 4, texture = 2, component_id = 11 }
-- },
-- props = {
-- { drawable = 27, prop_id = 0, texture = 0 },
-- { drawable = 0, prop_id = 1, texture = 0 },
-- { drawable = 0, prop_id = 2, texture = 0 },
-- { drawable = 0, prop_id = 3, texture = 0 },
-- { drawable = 0, prop_id = 4, texture = 0 },
-- { drawable = 0, prop_id = 5, texture = 0 },
-- { drawable = 0, prop_id = 6, texture = 0 },
-- { drawable = 0, prop_id = 7, texture = 0 },
-- { drawable = 0, prop_id = 8, texture = 0 },
-- { drawable = 0, prop_id = 9, texture = 0 },
-- { drawable = 0, prop_id = 10, texture = 0 },
-- { drawable = 0, prop_id = 11, texture = 0 },
-- { drawable = 0, prop_id = 12, texture = 0 },
-- { drawable = 0, prop_id = 13, texture = 0 }
-- }
-- },
-- particles = {
-- {
-- dict = "core",
-- ptfx = "ent_dst_electrical",
-- offset = vector3(0.0, 1.0, 0.0),
-- looped = true
-- },
-- {
-- dict = "core",
-- ptfx = "ent_dst_electrical",
-- offset = vector3(0.0, -1.0, 0.0),
-- rotation = vector3(0.0, 0.0, 180.0),
-- looped = true,
-- loopLength = 1000
-- }
-- },
-- targets = {
-- {
-- label = "Follow Test",
-- distance = 2,
-- description = "A test particle for demonstration purposes.",
-- onSelect = function (entityData, entity)
-- FreezeEntityPosition(entity, false)
-- Bridge.ClientEntity.Set(entityData.id, "follow", {
-- target = PlayerPedId()
-- })
-- end
-- }
-- },
-- -- OnUpdate = function(entityData)
-- -- end,
-- })
-- -- Wait(5000)
-- Bridge.ClientEntity.Set(data.id, "targets", {
-- label = "This should be the new label",
-- distance = 2,
-- description = "Herpa derpa gihad",
-- onSelect = function (entityData, entity)
-- print("round 2 baby", entityData.id)
-- end
-- })
-- end, false)
-- Bridge.ClientEntity.Behaviors.Create("plate", {
-- tag = "something",
-- OnCreate = function(entityData)
-- end,
-- OnSpawn = function(entityData)
-- end,
-- OnUpdate = function(entityData)
-- -- Update logic here
-- end,
-- OnRemove = function(entityData)
-- end,
-- OnDestroy = function(entityData)
-- end
-- })
RegisterCommand("ClientEntityFreeze", function()
local position = GetEntityCoords(PlayerPedId())
local data = Bridge.ClientEntity.Create({
model = "mp_m_freemode_01",
coords = position,
entityType = "ped",
freeze = true
})
Wait(10000)
Bridge.ClientEntity.Set(data.id, "freeze", false)
end, false)
RegisterCommand("ClientEntityFollow", function()
local position = GetEntityCoords(PlayerPedId())
local serverId = GetPlayerServerId(PlayerId())
local data = Bridge.ClientEntity.Create({
model = "mp_m_freemode_01",
coords = position,
entityType = "ped",
freeze = false,
follow = {
speed = 3.0,
target = serverId,
distance = 5.0
}
})
print(data.id)
end, false)
RegisterCommand("ClientEntityWeapon", function()
local position = GetEntityCoords(PlayerPedId())
local data = Bridge.ClientEntity.Create({
model = "mp_m_freemode_01",
coords = position,
entityType = "ped",
weapon = {
name = "WEAPON_PISTOL",
ammo = 100
}
})
end, false)
RegisterCommand("ClientEntityAttach", function()
local position = GetEntityCoords(PlayerPedId())
local serverId = GetPlayerServerId(PlayerId())
Bridge.ClientEntity.Create({
id = "attach_" .. math.random(1, 10000),
model = "mp_m_freemode_01",
coords = position,
entityType = "ped",
attach = {
target = serverId,
bone = 57005
}
})
end, false)
RegisterCommand("ClientEntityScenarios", function()
local position = GetEntityCoords(PlayerPedId())
Bridge.ClientEntity.Create({
id = "scenarios_" .. math.random(1, 10000),
model = "mp_m_freemode_01",
coords = position,
entityType = "ped",
scenarios = {
name = "WORLD_HUMAN_CLIPBOARD",
introClip = true,
duration = 20000
}
})
end, false)
RegisterCommand("ClientEntityAnim", function()
local position = GetEntityCoords(PlayerPedId())
Bridge.ClientEntity.Create({
id = "anim_" .. math.random(1, 10000),
model = "mp_m_freemode_01",
coords = position,
entityType = "ped",
anim = {
dict = "anim@mp_player_intcelebrationmale@wave",
name = "wave",
flags = 49,
duration = -1,
onComplete = function(entityData)
Bridge.ClientEntity.Set(entityData.id, "anim", {
dict = "rcmnigel1c",
name = "hailing_whistle_waive_a",
flags = entityData.anim.flags,
duration = 10000,
onComplete = function(entityData)
Bridge.ClientEntity.Set(entityData.id, "anim", {
dict = "timetable@denice@ig_1",
name = "idle_b",
flags = entityData.anim.flags,
duration = 10000,
onComplete = function(entityData)
print("hello")
end
})
end
})
end
}
})
end, false)
RegisterCommand("ClientEntityClothing", function()
local position = GetEntityCoords(PlayerPedId())
Bridge.ClientEntity.Create({
id = "clothing_" .. math.random(1, 10000),
model = "mp_m_freemode_01",
coords = position,
entityType = "ped",
clothing = {
components = {
{ drawable = 0, texture = 0, component_id = 0 },
{ drawable = 0, texture = 0, component_id = 1 },
{ drawable = 19, texture = 0, component_id = 2 },
{ drawable = 6, texture = 0, component_id = 3 },
{ drawable = 0, texture = 0, component_id = 4 },
{ drawable = 0, texture = 0, component_id = 5 },
{ drawable = 0, texture = 0, component_id = 6 },
{ drawable = 0, texture = 0, component_id = 7 },
{ drawable = 23, texture = 0, component_id = 8 },
{ drawable = 0, texture = 0, component_id = 9 },
{ drawable = 0, texture = 0, component_id = 10 },
{ drawable = 4, texture = 2, component_id = 11 }
},
props = {
{ drawable = 27, prop_id = 0, texture = 0 },
{ drawable = 0, prop_id = 1, texture = 0 },
{ drawable = 0, prop_id = 2, texture = 0 },
{ drawable = 0, prop_id = 3, texture = 0 },
{ drawable = 0, prop_id = 4, texture = 0 },
{ drawable = 0, prop_id = 5, texture = 0 },
{ drawable = 0, prop_id = 6, texture = 0 },
{ drawable = 0, prop_id = 7, texture = 0 },
{ drawable = 0, prop_id = 8, texture = 0 },
{ drawable = 0, prop_id = 9, texture = 0 },
{ drawable = 0, prop_id = 10, texture = 0 },
{ drawable = 0, prop_id = 11, texture = 0 },
{ drawable = 0, prop_id = 12, texture = 0 },
{ drawable = 0, prop_id = 13, texture = 0 }
}
}
})
end, false)
RegisterCommand("ClientEntityParticles", function()
local position = GetEntityCoords(PlayerPedId())
Bridge.ClientEntity.Create({
id = "particles_" .. math.random(1, 10000),
model = "mp_m_freemode_01",
coords = position,
entityType = "ped",
particles = {
{
dict = "core",
ptfx = "ent_dst_electrical",
offset = vector3(0.0, 1.0, 0.0),
looped = true
},
{
dict = "core",
ptfx = "ent_dst_electrical",
offset = vector3(0.0, -1.0, 0.0),
rotation = vector3(0.0, 0.0, 180.0),
looped = true,
loopLength = 1000
}
}
})
end, false)
RegisterCommand("ClientEntityTargets", function()
local position = GetEntityCoords(PlayerPedId())
local derp = Bridge.ClientEntity.Create({
id = "targets_" .. math.random(1, 10000),
model = "mp_m_freemode_01",
coords = position,
entityType = "ped",
targets = {
{
label = "Initial test",
distance = 2,
description = "A test particle for demonstration purposes.",
onSelect = function (entityData, entity)
print("Selected entity:", entityData.id)
end
}
}
})
Wait(10000)
Bridge.ClientEntity.Set(derp.id, "targets",
{
{
label = "Follow Test",
distance = 2,
description = "A test particle for demonstration purposes.",
onSelect = function (entityData, entity)
Bridge.ClientEntity.Set(entityData.id, "freeze", false)
Bridge.ClientEntity.Set(entityData.id, "follow", {
target = PlayerPedId()
})
end
}
}
)
end, false)
+60
View File
@@ -0,0 +1,60 @@
Bridge = Bridge or exports['community_bridge']:Bridge()
RegisterCommand("dialogue", function()
local pos = GetOffsetFromEntityInWorldCoords(PlayerPedId(), 0, 2.0, 0)
local timeout = 500
local model = `a_f_y_hipster_01`
RequestModel(model)
while not HasModelLoaded(model) do
Wait(0)
timeout = timeout - 1
if timeout == 0 then
print("Failed to load model")
return
end
end
local ped = CreatePed(0, model, pos.x, pos.y, pos.z, 0.0, false, false)
SetEntityHeading(ped, 50.0)
local characterData = {
entity = ped,
offset = vector3(0, 0, 0),
rotationOffset = vector3(0, 0, 0)
}
Bridge.Dialogue.Open("Akmed", "Hello how are you doing my friend?", ped, {
{
label = "Trade with me",
id = 'something',
},
{
label = "Goodbye",
id = 'someotherthing',
},
},
function(selectedId)
if selectedId == 'something' then
Dialogue.Open( "Akmed" , "Thank you for wanting to purchase me lucky charms", characterData, {
{
label = "Fuck off",
id = 'something',
},
{
label = "Goodbye",
id = 'someotherthing',
},
},
function(selectedId)
DeleteEntity(ped)
if selectedId == "something" then
print("You hate lucky charms")
else
print("Thanks for keeping it civil")
end
end)
else
DeleteEntity(ped)
end
end)
end)
+115
View File
@@ -0,0 +1,115 @@
Bridge = Bridge or exports['community_bridge']:Bridge()
RegisterCommand("ServerEntityStash", function(src)
local position = GetEntityCoords(GetPlayerPed(src)) - vector3(0,0,1)
Bridge.ServerEntity.Create({
model = "mp_m_freemode_01",
coords = position,
entityType = "ped",
stash = {
label = "Test Stash",
slots = 20,
maxWeight = 10000,
target = {
label = "Open Stash",
description = "Access the stash to store or retrieve items.",
icon = "fas fa-boxes"
}
}
})
end, false)
RegisterCommand("ServerEntityScenarios", function(src)
local position = GetEntityCoords(GetPlayerPed(src)) - vector3(0,0,1)
Bridge.ServerEntity.Create({
model = "mp_m_freemode_01",
coords = position,
entityType = "ped",
scenarios = {
name = "WORLD_HUMAN_CLIPBOARD",
introClip = true,
duration = 20000
}
})
end, false)
RegisterCommand("ServerEntityAnim", function(src)
local position = GetEntityCoords(GetPlayerPed(src)) - vector3(0,0,1)
Bridge.ServerEntity.Create({
model = "mp_m_freemode_01",
coords = position,
entityType = "ped",
anim = {
dict = "anim@mp_player_intcelebrationmale@wave",
name = "wave",
flags = 49,
duration = -1,
}
})
end, false)
RegisterCommand("ServerEntityParticles", function(src)
local position = GetEntityCoords(GetPlayerPed(src)) - vector3(0,0,1)
Bridge.ServerEntity.Create({
model = "mp_m_freemode_01",
coords = position,
entityType = "ped",
particles = {
{
dict = "core",
ptfx = "ent_dst_electrical",
offset = vector3(0.0, 1.0, 0.0),
looped = true
},
{
dict = "core",
ptfx = "ent_dst_electrical",
offset = vector3(0.0, -1.0, 0.0),
rotation = vector3(0.0, 0.0, 180.0),
looped = true,
loopLength = 1000
}
}
})
end, false)
RegisterCommand("ServerEntityClothing", function(src)
local position = GetEntityCoords(GetPlayerPed(src)) - vector3(0,0,1)
Bridge.ServerEntity.Create({
model = "mp_m_freemode_01",
coords = position,
entityType = "ped",
clothing = {
components = {
{ drawable = 0, texture = 0, component_id = 0 },
{ drawable = 0, texture = 0, component_id = 1 },
{ drawable = 19, texture = 0, component_id = 2 },
{ drawable = 6, texture = 0, component_id = 3 },
{ drawable = 0, texture = 0, component_id = 4 },
{ drawable = 0, texture = 0, component_id = 5 },
{ drawable = 0, texture = 0, component_id = 6 },
{ drawable = 0, texture = 0, component_id = 7 },
{ drawable = 23, texture = 0, component_id = 8 },
{ drawable = 0, texture = 0, component_id = 9 },
{ drawable = 0, texture = 0, component_id = 10 },
{ drawable = 4, texture = 2, component_id = 11 }
},
props = {
{ drawable = 27, prop_id = 0, texture = 0 },
{ drawable = 0, prop_id = 1, texture = 0 },
{ drawable = 0, prop_id = 2, texture = 0 },
{ drawable = 0, prop_id = 3, texture = 0 },
{ drawable = 0, prop_id = 4, texture = 0 },
{ drawable = 0, prop_id = 5, texture = 0 },
{ drawable = 0, prop_id = 6, texture = 0 },
{ drawable = 0, prop_id = 7, texture = 0 },
{ drawable = 0, prop_id = 8, texture = 0 },
{ drawable = 0, prop_id = 9, texture = 0 },
{ drawable = 0, prop_id = 10, texture = 0 },
{ drawable = 0, prop_id = 11, texture = 0 },
{ drawable = 0, prop_id = 12, texture = 0 },
{ drawable = 0, prop_id = 13, texture = 0 }
}
}
})
end, false)
+53
View File
@@ -0,0 +1,53 @@
Bridge = Bridge or exports['community_bridge']:Bridge()
RegisterCommand('testboxzone', function(source, args, rawCommand)
local playerPos = GetEntityCoords(PlayerPedId())
Bridge.Zones.Create("box", {
coords = vector3(playerPos.x, playerPos.y, playerPos.z),
size = vector3(2, 2, 6),
heading = 90,
debug = true,
onEnter = function(data)
print("Entered Zone: " .. data.id)
end,
onExit = function(data)
print("Exited Zone:")
end
})
end, false)
RegisterCommand('testpolyzone', function(source, args, rawCommand)
local playerPos = GetEntityCoords(PlayerPedId())
Bridge.Zones.Create("poly", {
points = {
vector3(playerPos.x - 1, playerPos.y - 1, playerPos.z),
vector3(playerPos.x + 1, playerPos.y - 1, playerPos.z),
vector3(playerPos.x + 1, playerPos.y + 1, playerPos.z),
vector3(playerPos.x - 1, playerPos.y + 1, playerPos.z)
},
size = vector3(1, 1, 1),
heading = 90,
debug = true,
onEnter = function(data)
print("Entered Zone: " .. data.id)
end,
onExit = function(data)
print("Exited Zone:")
end
})
end, false)
RegisterCommand('testspherezone', function(source, args, rawCommand)
local playerPos = GetEntityCoords(PlayerPedId())
Bridge.Zones.Create("sphere", {
coords = vector3(playerPos.x, playerPos.y, playerPos.z),
radius = 2.0,
debug = true,
onEnter = function(data)
print("Entered Zone: " .. data.id)
end,
onExit = function(data)
print("Exited Zone:")
end
})
end, false)
+4 -5
View File
@@ -5,13 +5,12 @@ use_experimental_fxv2_oal 'yes'
author 'The Order of the Sacred Framework'
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.11.2'
version '0.12.0'
shared_scripts {
'@ox_lib/init.lua',
'settings/sharedConfig.lua',
'lib/init.lua',
'modules/math/*.lua',
'modules/locales/*.lua',
'modules/clothing/**/shared.lua',
}
@@ -61,6 +60,7 @@ client_scripts {
'modules/housing/**/client.lua',
'modules/skills/**/client.lua',
'modules/bossmenu/**/client.lua',
'modules/zones/**/client.lua',
'init.lua',
-- 'unit_tests/*.lua',
}
@@ -72,9 +72,8 @@ files {
'web/dist/assets/*.css',
'web/dist/assets/*.js',
'locales/*.json',
'lib/**/client/*.lua',
'lib/**/shared/*.lua',
'lib/**/server/*.lua',
'lib/**/**/*.lua',
'lib/**/**/**/*.lua',
'modules/**',
'settings/*.lua',
'lib/init.lua',
+3 -29
View File
@@ -20,31 +20,24 @@ function Bridge.RegisterModule(moduleName, moduleTable)
if BridgeSharedConfig.DebugLevel ~= 0 then
print("^2 Registering module:", moduleName, "^0")
end
-- remove __ENV as its not present in luajit at all from what ive read. Good find guys :P
Bridge[moduleName] = wrappedModule
_ENV[moduleName] = wrappedModule -- Add to the ENV table the modules so is more easy and safe to call from inside
_ENV.Bridge = Bridge -- Add the bridge too to the _ENV
exports(moduleName, function()
return wrappedModule
end)
--trigger update object event
TriggerEvent("Bridge:Refresh", moduleName, wrappedModule)
end
exports("RegisterModule", Bridge.RegisterModule)
--TODO: Create a way to overide functions or create a new functions for module
function Bridge.RegisterModuleFunction(moduleName, functionName, func)
assert(moduleName and functionName and func, string.format("Bridge.RegisterModuleFunction(%s, %s, %s) - Invalid arguments", moduleName, functionName, func))
Bridge[moduleName] = Bridge[moduleName] or {}
Bridge[moduleName][functionName] = func
--trigger update object event
TriggerEvent("Bridge:Refresh", moduleName, Bridge[moduleName])
end
--Bridge
Bridge.RegisterModule("Framework", Framework)
Bridge.RegisterModule("BossMenu", BossMenu)
Bridge.RegisterModule("Inventory", Inventory)
@@ -58,24 +51,9 @@ Bridge.RegisterModule("Dispatch", Dispatch)
Bridge.RegisterModule("Shops", Shops)
Bridge.RegisterModule("Housing", Housing)
Bridge.RegisterModule("Version", Version)
--lib
-- Bridge.RegisterModule("Tables", cLib.Tables)
-- Bridge.RegisterModule("Math", cLib.Math)
-- Bridge.RegisterModule("Prints", cLib.Prints)
-- Bridge.RegisterModule("Callback", cLib.Callback)
-- --new
Bridge.RegisterModule("Require", Require)
-- Bridge.RegisterModule("Ids", cLib.Ids)
-- Bridge.RegisterModule("ReboundEntities", cLib.ReboundEntities)
-- Bridge.RegisterModule("LA", cLib.LA)
-- Bridge.RegisterModule("Perlin", cLib.Perlin)
-- Bridge.RegisterModule("Actions", cLib.Actions)
-- Bridge.RegisterModule("Cache", cLib.Cache)
Bridge.RegisterModule("Skills", Skills)
for k, v in pairs(cLib) do
if v then
Bridge.RegisterModule(k, v)
@@ -86,18 +64,13 @@ exports('Bridge', function()
return Bridge
end)
-- ▄▀▀ ██▀ █▀▄ █ █ ██▀ █▀▄
-- ▄█▀ █▄▄ █▀▄ ▀▄▀ █▄▄ █▀▄
if not IsDuplicityVersion() then goto client end
Bridge.RegisterModule('Version', Version)
Bridge.RegisterModule('Banking', Banking)
-- ▄▀▀ █ █ ██▀ █▄ █ ▀█▀
-- ▀▄▄ █▄▄ █ █▄▄ █ ▀█ █
if IsDuplicityVersion() then return end
::client::
Bridge.RegisterModule("Fuel", Fuel)
Bridge.RegisterModule("Input", Input)
Bridge.RegisterModule("ProgressBar", ProgressBar)
@@ -106,4 +79,5 @@ Bridge.RegisterModule("Weather", Weather)
Bridge.RegisterModule("Target", Target)
Bridge.RegisterModule("Menu", Menu)
Bridge.RegisterModule("Dialogue", Dialogue)
Bridge.RegisterModule("Dialogue", Dialogue)
Bridge.RegisterModule("Zones", cZones)
-23
View File
@@ -1,23 +0,0 @@
-- Test file for FiveM Community Bridge Extension
-- Try the following to test extension features:
-- 1. Type "CommunityBridge." (with the dot) and you should see auto-completion
-- CommunityBridge.
-- 2. Type "AddEventHandler" and see parameter hints
-- AddEventHandler(
-- 3. Hover over these function names to see documentation:
-- GetPlayerData, SetPlayerData, TriggerEvent, RegisterNetEvent
-- 4. Try these snippets (type the word and press Tab):
-- event
-- thread
-- command
-- cbget
-- cbset
-- 5. Test signature help - start typing a function call:
-- CommunityBridge.GetPlayerData(
print("Extension test file loaded")
File renamed without changes.
-329
View File
@@ -1,329 +0,0 @@
-- -- DUI (Direct User Interface) Manager for FiveM
-- -- Basic table-based implementation with full mouse support
-- ---@class DUI
-- DUI = {}
-- -- Constants
-- local DEFAULT_WIDTH <const> = 1280
-- local DEFAULT_HEIGHT <const> = 720
-- -- Store active DUI instances
-- local activeInstances = {}
-- local instanceCounter = 0
-- -- Mouse tracking state
-- local mouseState = {
-- tracking = false,
-- activeId = nil,
-- lastX = 0,
-- lastY = 0,
-- isPressed = false,
-- currentButton = nil
-- }
-- -- Mouse button constants
-- local MOUSE_BUTTONS <const> = {
-- LEFT = "left",
-- MIDDLE = "middle",
-- RIGHT = "right"
-- }
-- ---@class DUIInstance
-- ---@field id number Unique identifier for this DUI instance
-- ---@field url string URL loaded in the DUI
-- ---@field width number Width of the DUI
-- ---@field height number Height of the DUI
-- ---@field handle number DUI browser handle
-- ---@field txd string Texture dictionary name
-- ---@field txn string Texture name
-- ---@field active boolean Whether the DUI is active
-- ---@field trackMouse boolean Whether mouse tracking is enabled for this instance
-- ---@field mouseScale table<string, number> Scale factors for mouse coordinates
-- -- Create a new DUI instance
-- ---@param url string URL to load
-- ---@param width? number Width of the DUI (default: 1280)
-- ---@param height? number Height of the DUI (default: 720)
-- ---@return number|nil id The DUI instance ID if successful, nil if failed
-- function DUI.Create(url, width, height)
-- if not url or type(url) ~= "string" then
-- return print("DUI.Create: URL is required and must be a string")
-- end
-- width = width or DEFAULT_WIDTH
-- height = height or DEFAULT_HEIGHT
-- instanceCounter = instanceCounter + 1
-- local id = instanceCounter
-- local handle = CreateDui(url, width, height)
-- if not handle then
-- return print("DUI.Create: Failed to create DUI instance")
-- end
-- local instance = {
-- id = id,
-- url = url,
-- width = width,
-- height = height,
-- handle = handle,
-- txd = "dui_" .. id,
-- txn = "texture_" .. id,
-- active = true,
-- trackMouse = false,
-- mouseScale = {
-- x = 1.0,
-- y = 1.0
-- }
-- }
-- -- Create runtime texture
-- local duiHandle = GetDuiHandle(handle)
-- CreateRuntimeTextureFromDuiHandle(CreateRuntimeTxd(instance.txd), instance.txn, duiHandle)
-- activeInstances[id] = instance
-- return id
-- end
-- -- Destroy a DUI instance
-- ---@param id number DUI instance ID
-- ---@return boolean success Whether the operation was successful
-- function DUI.Destroy(id)
-- local instance = activeInstances[id]
-- if not instance then return false end
-- if instance.handle then
-- DestroyDui(instance.handle)
-- end
-- activeInstances[id] = nil
-- return true
-- end
-- -- Set URL for a DUI instance
-- ---@param id number DUI instance ID
-- ---@param url string New URL to load
-- ---@return boolean success Whether the operation was successful
-- function DUI.SetURL(id, url)
-- local instance = activeInstances[id]
-- if not instance then return false end
-- SetDuiUrl(instance.handle, url)
-- instance.url = url
-- return true
-- end
-- -- Send a message to the DUI
-- ---@param id number DUI instance ID
-- ---@param message table Message to send (will be JSON encoded)
-- ---@return boolean success Whether the operation was successful
-- function DUI.SendMessage(id, message)
-- local instance = activeInstances[id]
-- if not instance then return false end
-- SendDuiMessage(instance.handle, json.encode(message))
-- return true
-- end
-- -- Mouse interaction functions
-- -- Move mouse cursor on DUI
-- ---@param id number DUI instance ID
-- ---@param x number X coordinate
-- ---@param y number Y coordinate
-- ---@return boolean success Whether the operation was successful
-- function DUI.MoveMouse(id, x, y)
-- local instance = activeInstances[id]
-- if not instance then return false end
-- SendDuiMouseMove(instance.handle, x, y)
-- return true
-- end
-- -- Simulate mouse button press
-- ---@param id number DUI instance ID
-- ---@param button "left"|"middle"|"right" Mouse button to simulate
-- ---@return boolean success Whether the operation was successful
-- function DUI.MouseDown(id, button)
-- local instance = activeInstances[id]
-- if not instance then return false end
-- if not MOUSE_BUTTONS[button:upper()] then
-- return print("DUI.MouseDown: Invalid button. Must be 'left', 'middle', or 'right'")
-- end
-- -- Update mouse state
-- if instance.trackMouse then
-- mouseState.isPressed = true
-- mouseState.currentButton = button
-- end
-- SendDuiMouseDown(instance.handle, button)
-- return true
-- end
-- -- Simulate mouse button release
-- ---@param id number DUI instance ID
-- ---@param button "left"|"middle"|"right" Mouse button to simulate
-- ---@return boolean success Whether the operation was successful
-- function DUI.MouseUp(id, button)
-- local instance = activeInstances[id]
-- if not instance then return false end
-- if not MOUSE_BUTTONS[button:upper()] then
-- return print("DUI.MouseUp: Invalid button. Must be 'left', 'middle', or 'right'")
-- end
-- -- Update mouse state
-- if instance.trackMouse then
-- mouseState.isPressed = false
-- mouseState.currentButton = nil
-- end
-- SendDuiMouseUp(instance.handle, button)
-- return true
-- end
-- -- Simulate mouse wheel movement
-- ---@param id number DUI instance ID
-- ---@param deltaY number Vertical scroll amount
-- ---@param deltaX number Horizontal scroll amount
-- ---@return boolean success Whether the operation was successful
-- function DUI.MouseWheel(id, deltaY, deltaX)
-- local instance = activeInstances[id]
-- if not instance then return false end
-- SendDuiMouseWheel(instance.handle, deltaY, deltaX)
-- return true
-- end
-- -- Click helper function (combines MoveMouse, MouseDown, and MouseUp)
-- ---@param id number DUI instance ID
-- ---@param x number X coordinate
-- ---@param y number Y coordinate
-- ---@param button? "left"|"middle"|"right" Mouse button to click (default: "left")
-- ---@return boolean success Whether the operation was successful
-- function DUI.Click(id, x, y, button)
-- button = button or "left"
-- if not DUI.MoveMouse(id, x, y) then return false end
-- if not DUI.MouseDown(id, button) then return false end
-- -- Small delay to simulate real click
-- Citizen.Wait(50)
-- return DUI.MouseUp(id, button)
-- end
-- -- Enable or disable mouse tracking for a DUI instance
-- ---@param id number DUI instance ID
-- ---@param enabled boolean Whether to enable mouse tracking
-- ---@param scaleX? number Scale factor for X coordinates (default: 1.0)
-- ---@param scaleY? number Scale factor for Y coordinates (default: 1.0)
-- ---@return boolean success Whether the operation was successful
-- function DUI.TrackMouse(id, enabled, scaleX, scaleY)
-- local instance = activeInstances[id]
-- if not instance then return false end
-- instance.trackMouse = enabled
-- instance.mouseScale.x = scaleX or 1.0
-- instance.mouseScale.y = scaleY or 1.0
-- if enabled then
-- mouseState.tracking = true
-- mouseState.activeId = id
-- elseif mouseState.activeId == id then
-- mouseState.tracking = false
-- mouseState.activeId = nil
-- end
-- return true
-- end
-- -- Update mouse coordinates from screen position
-- ---@param screenX number Screen X coordinate
-- ---@param screenY number Screen Y coordinate
-- ---@return boolean updated Whether coordinates were updated
-- local function UpdateMousePosition(screenX, screenY)
-- if not mouseState.tracking or not mouseState.activeId then return false end
-- local instance = activeInstances[mouseState.activeId]
-- if not instance or not instance.trackMouse then return false end
-- -- Scale coordinates based on DUI dimensions and scale factors
-- local scaledX = screenX * instance.mouseScale.x
-- local scaledY = screenY * instance.mouseScale.y
-- -- Only update if position changed
-- if scaledX ~= mouseState.lastX or scaledY ~= mouseState.lastY then
-- mouseState.lastX = scaledX
-- mouseState.lastY = scaledY
-- DUI.MoveMouse(mouseState.activeId, scaledX, scaledY)
-- return true
-- end
-- return false
-- end
-- -- Mouse tracking thread
-- Citizen.CreateThread(function()
-- while true do
-- if mouseState.tracking and mouseState.activeId then
-- local instance = activeInstances[mouseState.activeId]
-- if instance and instance.trackMouse then
-- -- Get current cursor position
-- local screenX, screenY = GetNuiCursorPosition()
-- UpdateMousePosition(screenX, screenY)
-- -- Handle held mouse buttons
-- if mouseState.isPressed and mouseState.currentButton then
-- -- Keep the button pressed state
-- SendDuiMouseDown(instance.handle, mouseState.currentButton)
-- end
-- end
-- end
-- Citizen.Wait(0)
-- end
-- end)
-- -- Utility functions
-- -- Get textures for a DUI instance
-- ---@param id number DUI instance ID
-- ---@return string|nil txd, string|nil txn Texture dictionary and name, or nil if instance not found
-- function DUI.GetTextures(id)
-- local instance = activeInstances[id]
-- if not instance then return nil, nil end
-- return instance.txd, instance.txn
-- end
-- -- Check if a DUI instance exists
-- ---@param id number DUI instance ID
-- ---@return boolean exists Whether the instance exists and is active
-- function DUI.Exists(id)
-- local instance = activeInstances[id]
-- return instance ~= nil and instance.active
-- end
-- -- Get all active DUI instances
-- ---@return table<number, DUIInstance> instances Table of active DUI instances
-- function DUI.GetActiveInstances()
-- return activeInstances
-- end
-- -- Cleanup all DUI instances
-- function DUI.CleanupAll()
-- for id in pairs(activeInstances) do
-- DUI.Destroy(id)
-- end
-- end
-- -- Automatic cleanup on resource stop
-- AddEventHandler('onResourceStop', function(resourceName)
-- if GetCurrentResourceName() ~= resourceName then return end
-- DUI.CleanupAll()
-- end)
-- return DUI
+136 -138
View File
@@ -1,52 +1,59 @@
Utility = Utility or Require("lib/utility/client/utility.lua")
Ids = Ids or Require("lib/utility/shared/ids.lua")
Point = Point or Require("lib/points/client/points.lua")
ClientEntityActions = ClientEntityActions or Require("lib/entities/client/client_entity_actions_ext.lua") -- Added
Behaviors = Behaviors or Require("lib/entities/shared/behaviors.lua")
local Entities = {} -- Stores entity data received from server
ClientEntity = {} -- Renamed from BaseEntity
ClientEntity = {
Invoked = {}
} -- Renamed from BaseEntity
ClientEntity.Behaviors = Behaviors
--------------------
local function SpawnEntity(entityData)
entityData = entityData and entityData.args
if entityData.spawned and DoesEntityExist(entityData.spawned) then return end -- Already spawned
local loaded, model = Utility.LoadModel(entityData.model)
if not loaded then
print(string.format("[ClientEntity] Failed to load model %s for entity %s", entityData.model, entityData.id))
return
end
if entityData.model then
local loaded, model = Utility.LoadModel(entityData.model)
if not loaded then
print(string.format("[ClientEntity] Failed to load model %s for entity %s", entityData.model, entityData.id))
return
end
local entity = nil
local coords = entityData.coords
local rotation = entityData.rotation or vector3(0.0, 0.0, entityData.heading or 0.0) -- Default rotation if not provided
local entity = nil
local coords = entityData.coords
local rotation = entityData.rotation or vector3(0.0, 0.0, entityData.heading or 0.0) -- Default rotation if not provided
if entityData.entityType == 'object' then
entity = CreateObject(model, coords.x, coords.y, coords.z, false, false, false)
SetEntityRotation(entity, rotation.x, rotation.y, rotation.z, 2, true)
elseif entityData.entityType == 'ped' then
entity = CreatePed(4, model, coords.x, coords.y, coords.z, type(rotation) == 'number' and rotation or rotation.z, false, false)
elseif entityData.entityType == 'vehicle' then
entity = CreateVehicle(model, coords.x, coords.y, coords.z, type(rotation) == 'number' and rotation or rotation.z, false, false)
else
print(string.format("[ClientEntity] Unknown entity type '%s' for entity %s", entityData.entityType, entityData.id))
end
if entity and model then
entityData.spawned = entity
SetModelAsNoLongerNeeded(model)
SetEntityAsMissionEntity(entity, true, true)
FreezeEntityPosition(entity, true)
else
SetModelAsNoLongerNeeded(model)
if entityData.entityType == 'object' then
entity = CreateObject(model, coords.x, coords.y, coords.z, false, false, false)
SetEntityRotation(entity, rotation.x, rotation.y, rotation.z, 2, true)
elseif entityData.entityType == 'ped' then
entity = CreatePed(4, model, coords.x, coords.y, coords.z, type(rotation) == 'number' and rotation or rotation.z, false, false)
elseif entityData.entityType == 'vehicle' then
entity = CreateVehicle(model, coords.x, coords.y, coords.z, type(rotation) == 'number' and rotation or rotation.z, false, false)
else
print(string.format("[ClientEntity] Unknown entity type '%s' for entity %s", entityData.entityType, entityData.id))
end
if entity and model then
entityData.spawned = entity
SetModelAsNoLongerNeeded(model)
SetEntityAsMissionEntity(entity, true, true)
FreezeEntityPosition(entity, true)
else
SetModelAsNoLongerNeeded(model)
end
end
if entityData.OnSpawn then
pcall(function (...)
return entityData.OnSpawn(entityData)
end)
end)
end
Behaviors.Trigger("OnSpawn", entityData)
end
local function RemoveEntity(entityData)
entityData = entityData and entityData.args or entityData
if not entityData then return end
Behaviors.Trigger("OnRemove", entityData)
if entityData.OnRemove then
pcall(function (...)
return entityData.OnRemove(entityData)
@@ -60,13 +67,63 @@ local function RemoveEntity(entityData)
end
end
local function UpdateEntity(_entityData)
local entityData = ClientEntity.Get(_entityData.id)
if not entityData then return end
if entityData.OnUpdate then
pcall(function (...)
return entityData.OnUpdate(entityData)
end)
end
Behaviors.Trigger("OnUpdate", entityData)
local coords = vector3(entityData.coords.x, entityData.coords.y, entityData.coords.z)
entityData.oldCoords = entityData.oldCoords and vector3(entityData.oldCoords.x, entityData.oldCoords.y, entityData.oldCoords.z) or coords
local dist = #(coords - entityData.oldCoords)
if entityData.oldCoords and dist > 0.5 then
if entityData.spawned then
SetEntityCoords(entityData.spawned, coords.x, coords.y, coords.z, false, false, false, true)
end
-- ClientEntity.UpdateCoords(entityData.id, entityData.coords)
if entityData.OnMove then
pcall(function (...)
return entityData.OnMove(entityData)
end)
end
Behaviors.Trigger("OnMove", entityData, entityData.oldCoords, entityData.coords)
end
if not entityData.oldRotation or entityData.oldRotation ~= entityData.rotation then
if entityData.spawned and DoesEntityExist(entityData.spawned) then
if entityData.entityType == 'object' then
SetEntityRotation(entityData.spawned, entityData.rotation.x, entityData.rotation.y, entityData.rotation.z, 2, true)
else -- Ped/Vehicle heading
SetEntityHeading(entityData.spawned, type(entityData.rotation) == 'number' and entityData.rotation or entityData.rotation.z)
end
end
entityData.oldRotation = entityData.rotation
end
if entityData.freeze ~= nil and entityData.spawned and IsEntityPositionFrozen(entityData.spawned) then
FreezeEntityPosition(entityData.spawned, entityData.freeze)
end
end
--- Registers an entity received from the server and sets up proximity spawning.
-- @param entityData table Data received from the server via 'community_bridge:client:CreateEntity'
function ClientEntity.Create(entityData)
entityData.id = entityData.id or Ids.CreateUniqueId(Entities)
if Entities[entityData.id] then return Entities[entityData.id] end -- Already registered
Entities[entityData.id] = entityData
return Point.Register(entityData.id, entityData.coords, entityData.spawnDistance or 50.0, entityData, SpawnEntity, RemoveEntity, function() end)
if Entities[entityData.id] then return Entities[entityData.id] end
entityData.rotation = entityData.rotation or vector3(0.0, 0.0, entityData.heading or 0.0)
entityData.oldCoords = entityData.oldCoords or vector3(0.0, 0.0, 0.0)
entityData.oldRotation = entityData.rotation
entityData.invoked = entityData.invoked or GetInvokingResource() or "community_bridge"
local entityPoint = Point.Register(entityData.id, entityData.coords, entityData.spawnDistance or 50.0, entityData, SpawnEntity, RemoveEntity, UpdateEntity)
Entities[entityData.id] = entityPoint
ClientEntity.Invoked[entityData.invoked] = ClientEntity.Invoked[entityData.invoked] or {}
ClientEntity.Invoked[entityData.invoked][entityData.id] = entityData
Behaviors.Trigger("OnCreate", entityPoint)
return entityPoint
end
--Depricated use ClientEntity.Create instead
@@ -86,75 +143,31 @@ end
-- Depricated use ClientEntity.CreateBulk instead
ClientEntity.RegisterBulk = ClientEntity.CreateBulk
--- Unregisters an entity and removes it from the world if spawned.
-- @param id string|number The ID of the entity to unregister.
function ClientEntity.Destroy(id)
local entityData = Entities[id]
if not entityData then return end
Behaviors.Trigger("OnDestroy", entityData)
Point.Remove(id)
RemoveEntity(entityData)
RemoveEntity(entityData)
Entities[id] = nil
end
ClientEntity.Unregister = ClientEntity.Destroy
function ClientEntity.RegisterBehavior(id, behavior)
Behaviors.Create(id, behavior)
end
--- Updates the data for a registered entity.
-- @param id string|number The ID of the entity to update.
-- @param data table The data fields to update.
function ClientEntity.Update(id, data)
local entityData = Entities[id]
-- print(string.format("[ClientEntity] Updating entity %s", id))
if not entityData then return end
local needsPointUpdate = false
for key, value in pairs(data) do
if key == 'coords' and #(entityData.coords - value) > 0.1 then
needsPointUpdate = true
end
if key == 'spawnDistance' and entityData.spawnDistance ~= value then
needsPointUpdate = true
end
entityData[key] = value
end
-- If entity is currently spawned, apply updates
if entityData.spawned and DoesEntityExist(entityData.spawned) then
if data.coords then
SetEntityCoords(entityData.spawned, entityData.coords.x, entityData.coords.y, entityData.coords.z, false, false, false, true)
end
if data.rotation then
if entityData.entityType == 'object' then
SetEntityRotation(entityData.spawned, entityData.rotation.x, entityData.rotation.y, entityData.rotation.z, 2, true)
else -- Ped/Vehicle heading
SetEntityHeading(entityData.spawned, type(entityData.rotation) == 'number' and entityData.rotation or entityData.rotation.z)
end
end
if data.freeze ~= nil then
FreezeEntityPosition(entityData.spawned, data.freeze)
end
-- Add other updatable properties as needed
end
-- Update Point registration if coords or distance changed
if needsPointUpdate then
Point.Remove(id)
Point.Register(
entityData.id,
entityData.coords,
entityData.spawnDistance or 50.0,
SpawnEntity,
RemoveEntity,
nil,
entityData
)
end
if entityData.OnUpdate and type(entityData.OnUpdate) == 'function' then
entityData.OnUpdate(entityData, data)
end
--- Sets a key-value pair for a client entity.
---@param id any
---@param key any
---@param value any
---@return nil
function ClientEntity.Set(id, key, value)
local entityData = ClientEntity.Get(id)
if not entityData then return print(string.format("[ClientEntity] SetKey: Entity %s does not exist", id)) end
entityData[key] = value
end
function ClientEntity.Get(id)
@@ -165,10 +178,6 @@ function ClientEntity.GetAll()
return Entities
end
function ClientEntity.RegisterAction(name, func)
ClientEntityActions.RegisterAction(name, func)
end
function ClientEntity.OnCreate(_type, func)
ClientEntity.OnCreates = ClientEntity.OnCreates or {}
if not ClientEntity.OnCreates[_type] then
@@ -202,12 +211,21 @@ function ClientEntity.UpdateCoords(id, coords)
return
end
entityData.coords = coords
Point.UpdateCoords(id, coords)
if entityData.spawned and DoesEntityExist(entityData.spawned) then
SetEntityCoords(entityData.spawned, coords.x, coords.y, coords.z, false, false, false, true)
end
Point.UpdateCoords(id, coords)
end
function ClientEntity.ChangeModel(id, model)
local entityData = Entities[id]
if not entityData then return print(string.format("[ClientEntity] ChangeModel: Entity %s does not exist", id)) end
entityData.model = model
if not entityData.spawned or not DoesEntityExist(entityData.spawned) then return end
RemoveEntity(entityData)
SpawnEntity(entityData)
end
-- Network Event Handlers
RegisterNetEvent("community_bridge:client:CreateEntity", function(entityData)
ClientEntity.Create(entityData)
@@ -222,47 +240,21 @@ RegisterNetEvent("community_bridge:client:DeleteEntity", function(id)
end)
RegisterNetEvent("community_bridge:client:UpdateEntity", function(id, data)
ClientEntity.Update(id, data)
end)
-- New handler for entity actions
RegisterNetEvent("community_bridge:client:TriggerEntityAction", function(entityId, actionName, ...)
local entityData = Entities[entityId]
-- Check if entity exists locally (it doesn't need to be spawned to queue actions)
if entityData then
if actionName == "Stop" then
ClientEntityActions.StopAction(entityId)
elseif actionName == "Skip" then
ClientEntityActions.SkipAction(entityId)
else
print(string.format("[ClientEntity] Triggering action '%s' for entity %s", actionName, entityId))
local currentAction = ClientEntityActions.ActionQueue[entityId] and ClientEntityActions.ActionQueue[entityId][1]
ClientEntityActions.QueueAction(entityData, actionName, ...)
end
-- else
-- Optional: Log if action received but entity doesn't exist locally at all
-- print(string.format("[ClientEntity] Received action '%s' for non-existent entity %s.", actionName, entityId))
for k, v in pairs(data) do
ClientEntity.Set(id, k, v)
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
local Loaded = false
AddEventHandler('community_bridge:Client:OnPlayerLoaded', function(resourceName)
if Loaded then return end
Loaded = true
end)
AddEventHandler('onResourceStart', function(resourceName)
if resourceName ~= GetCurrentResourceName() then return end
if Loaded then return end
Loaded = true
end)
-- Resource Stop Cleanup
@@ -273,7 +265,13 @@ AddEventHandler('onResourceStop', function(resourceName)
RemoveEntity(entityData) -- Clean up spawned game entity
end
Entities = {} -- Clear local cache
else
for id, entityData in pairs(ClientEntity.Invoked[resourceName] or {}) do
Point.Remove(id) -- Clean up point registration
RemoveEntity(entityData) -- Clean up spawned game entity
Entities[id] = nil
end
end
end)
return ClientEntity
return ClientEntity
@@ -1,136 +0,0 @@
ClientEntityActions = {}
ClientEntityActions.ActionThreads = {} -- Store running action threads { [entityId] = thread }
ClientEntityActions.ActionQueue = {} -- Stores pending actions { [entityId] = {{name="ActionName", args={...}}, ...} }
ClientEntityActions.IsActionRunning = {} -- Tracks if an action is currently running { [entityId] = boolean }
ClientEntityActions.RegisteredActions = {} -- New: Registry for action implementations { [actionName] = function(entityData, ...) }
-- Forward declaration
--- Processes the next action in the queue for a given entity.
-- @param entityId string|number The ID of the entity.
function ClientEntityActions.ProcessNextAction(entityId)
if ClientEntityActions.IsActionRunning [entityId] then return end -- Already running something
local queue = ClientEntityActions.ActionQueue[entityId]
if not queue or #queue == 0 then return end -- Queue is empty
local nextAction = table.remove(queue, 1) -- Dequeue (FIFO)
local entityData = ClientEntity.Get(entityId) -- Assumes ClientEntity is accessible
-- Check if entity is still valid and spawned before starting next action
if not entityData or not entityData.spawned or not DoesEntityExist(entityData.spawned) then
-- Entity despawned while idle, clear queue and do nothing
ClientEntityActions.ActionQueue[entityId] = nil
return
end
-- Look up the action in the registry
local actionFunc = ClientEntityActions.RegisteredActions [nextAction.name]
if actionFunc then
-- print(string.format("[ClientEntityActions] Starting action '%s' for entity %s", nextAction.name, entityId))
ClientEntityActions.IsActionRunning [entityId] = true
-- Call the registered function
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.ActionQueue[entityId] = ClientEntityActions.ProcessNextAction(entityId)
end
end
--- Registers a custom action implementation.
-- The action function should handle its own logic, including threading if needed,
-- and MUST call ClientEntityActions.ProcessNextAction(entityData.id) when it completes or fails,
-- after setting ClientEntityActions.IsActionRunning [entityData.id] = false.
-- @param actionName string The name used to trigger this action.
-- @param actionFunc function The function to execute. Signature: function(entityData, ...)
function ClientEntityActions.RegisterAction(actionName, actionFunc)
if ClientEntityActions.RegisteredActions [actionName] then
print(string.format("[ClientEntityActions] WARNING: Overwriting registered action '%s'", actionName))
end
assert(type(actionName) == "string", "actionName must be a string")
ClientEntityActions.RegisteredActions[actionName] = actionFunc
-- print(string.format("[ClientEntityActions] Registered action: %s", actionName))
end
--- Queues an action for an entity. Starts processing if idle.
-- @param entityData table The entity data.
-- @param actionName string The name of the action.
-- @param ... any Arguments for the action.
function ClientEntityActions.QueueAction(entityData, actionName, ...)
local entityId = entityData.id
if not ClientEntityActions.ActionQueue[entityId] then
ClientEntityActions.ActionQueue[entityId] = {}
end
local actionArgs = {...}
table.insert(ClientEntityActions.ActionQueue[entityId], { name = actionName, args = actionArgs })
-- print(string.format("[ClientEntityActions] Queued action '%s' for entity %s. Queue size: %d", actionName, entityId, #ClientEntityActions.ActionQueue[entityId]))
-- If the entity isn't currently doing anything, start processing immediately
if not ClientEntityActions.IsActionRunning [entityId] then
ClientEntityActions.ProcessNextAction(entityId)
end
end
--- Stops the current action and clears the queue for a specific entity.
-- @param entityId string|number The ID of the entity.
function ClientEntityActions.StopAction(entityId)
-- print(string.format("[ClientEntityActions] Stopping all actions for entity %s", entityId))
ClientEntityActions.ActionQueue[entityId] = nil -- Clear the queue
ClientEntityActions.IsActionRunning [entityId] = false -- Mark as not running (this will stop loops in threads)
-- Stop current task/thread if applicable
if ClientEntityActions.ActionThreads[entityId] then
-- Lua threads stop themselves based on ClientEntityActions.IsActionRunning flag
ClientEntityActions.ActionThreads[entityId] = nil
end
-- Specific task clearing for peds
local entityData = ClientEntity.Get(entityId)
if entityData and entityData.spawned and DoesEntityExist(entityData.spawned) then
if IsEntityAPed(entityData.spawned) then
ClearPedTasksImmediately(entityData.spawned) -- Use Immediately for forceful stop
end
-- Other entity types might need different stop logic
end
end
--- Skips the current action and starts the next one in the queue, if any.
-- @param entityId string|number The ID of the entity.
function ClientEntityActions.SkipAction(entityId)
if not ClientEntityActions.IsActionRunning [entityId] then
-- print(string.format("[ClientEntityActions] SkipAction called for %s, but no action running.", entityId))
return -- Nothing to skip
end
-- print(string.format("[ClientEntityActions] Skipping current action for entity %s", entityId))
ClientEntityActions.IsActionRunning [entityId] = false -- Mark as not running (this will stop loops in threads)
-- Stop current task/thread if applicable
if ClientEntityActions.ActionThreads[entityId] then
ClientEntityActions.ActionThreads[entityId] = nil
end
local entityData = ClientEntity.Get(entityId)
if entityData and entityData.spawned and DoesEntityExist(entityData.spawned) then
if IsEntityAPed(entityData.spawned) then
ClearPedTasksImmediately(entityData.spawned)
end
end
-- Immediately try to process the next action
ClientEntityActions.ProcessNextAction(entityId)
end
-- Add server-callable functions for Stop and Skip
function ClientEntityActions.Stop(entityData)
ClientEntityActions.StopAction(entityData.id)
end
function ClientEntityActions.Skip(entityData)
ClientEntityActions.SkipAction(entityData.id)
end
return ClientEntityActions
+53 -76
View File
@@ -1,7 +1,10 @@
Ids = Ids or Require("lib/utility/shared/ids.lua")
Behaviors = Behaviors or Require("lib/entities/shared/behaviors.lua")
local Entities = {}
ServerEntity = {} -- Renamed from EntityRelay
ServerEntity.Behaviors = Behaviors
local Invoked = {}
--- Creates a server-side representation of an entity and notifies clients.
-- @param entityType string 'object', 'ped', or 'vehicle'
@@ -10,28 +13,26 @@ ServerEntity = {} -- Renamed from EntityRelay
-- @param rotation vector3|number Heading for peds/vehicles, rotation for objects
-- @param meta table Optional additional data
-- @return table The created entity data
function ServerEntity.New(id, entityType, model, coords, rotation, meta)
local self = meta or {}
function ServerEntity.New(id, entityType, model, coords, rotation, args)
assert(coords, "Coords are required for entity creation")
local self = args or {}
self.id = id or Ids.CreateUniqueId(Entities)
self.entityType = entityType
self.model = model
self.coords = coords
self.rotation = rotation or (entityType == 'object' and vector3(0.0, 0.0, 0.0) or 0.0) -- Default rotation or heading
self.resource = GetInvokingResource()
self.rotation = rotation or vector3(0.0, 0.0, 0.0)
local invoking = GetInvokingResource() or "community_bridge"
self.invoked = invoking
Invoked[invoking] = Invoked[invoking] or {}
table.insert(Invoked[invoking], self)
assert(self.id, "ID Failed to generate")
assert(self.entityType, "EntityType is required")
assert(self.model, "Model is required for entity creation")
assert(self.coords, "Coords are required for entity creation")
ServerEntity.Add(self)
return self
end
function ServerEntity.Create(id, entityType, model, coords, rotation, meta)
local self = ServerEntity.New(id, entityType, model, coords, rotation, meta)
if not self then
-- print("Failed to create entity with ID: " .. tostring(id))
return nil
end
function ServerEntity.Create(data)
local self = ServerEntity.New(data.id, data.entityType, data.model, data.coords, data.rotation or vector3(0.0, 0.0, data.heading or 0.0), data)
if not self then return nil end
Behaviors.Trigger("OnCreate", self)
TriggerClientEvent("community_bridge:client:CreateEntity", -1, self)
return self
end
@@ -40,15 +41,9 @@ function ServerEntity.CreateBulk(entities)
local createdEntities = {}
for _, entityData in pairs(entities) do
local id = entityData.id or Ids.CreateUniqueId(Entities)
local entity = ServerEntity.New(
id,
entityData.entityType,
entityData.model,
entityData.coords,
entityData.rotation,
entityData.meta
)
local entity = ServerEntity.New(id, entityData.entityType, entityData.model, entityData.coords, entityData.rotation, entityData)
createdEntities[id] = entity
Behaviors.Trigger("OnCreate", entity)
end
TriggerClientEvent("community_bridge:client:CreateEntities", -1, createdEntities)
return createdEntities
@@ -56,54 +51,19 @@ end
--- Deletes a server-side entity representation and notifies clients.
-- @param id string|number The ID of the entity to delete.
function ServerEntity.Delete(id)
if Entities[id] then
ServerEntity.Remove(id)
TriggerClientEvent("community_bridge:client:DeleteEntity", -1, id)
end
function ServerEntity.Destroy(id)
if not Entities[id] then return end
ServerEntity.Remove(id)
TriggerClientEvent("community_bridge:client:DeleteEntity", -1, id)
end
ServerEntity.Delete = ServerEntity.Destroy
--- Updates data for a server-side entity and notifies clients.
-- @param id string|number The ID of the entity to update.
-- @param data table The data fields to update.
function ServerEntity.Update(id, data)
local entity = Entities[id]
-- print("Updating entity: ", id, entity)
if not entity then return false end
for key, value in pairs(data) do
entity[key] = value
function ServerEntity.DestroyBulk(entityDatas)
for _, entityData in pairs(entityDatas) do
ServerEntity.Remove(entityData.id)
end
TriggerClientEvent("community_bridge:client:UpdateEntity", -1, id, data)
return true
end
--- Triggers a specific action on the client-side entity.
-- Clients will only execute the action if the entity is currently spawned for them.
-- @param entityId string|number The ID of the entity.
-- @param actionName string The name of the action to trigger (must match a function in ClientEntityActions).
-- @param ... any Additional arguments for the action function.
function ServerEntity.TriggerAction(entityId, actionName, endPosition, ...)
-- print("Triggering action: ", entityId, actionName, ...)
local entity = Entities[entityId]
if not entity then
print(string.format("[ServerEntity] Attempted to trigger action '%s' on non-existent entity %s", actionName, entityId))
return
end
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
print("[ServerEntity] DestroyBulk: Removed", #entityDatas, "entities")
TriggerClientEvent("community_bridge:client:DeleteBulk", -1, entityDatas)
end
function ServerEntity.Get(id)
@@ -118,18 +78,35 @@ function ServerEntity.Remove(id)
Entities[id] = nil
end
--- Updates data for a server-side entity and notifies clients.
-- @param id string|number The ID of the entity to update.
-- @param data table The data fields to update.
function ServerEntity.Set(id, data)
local entity = Entities[id]
if not entity then return false end
for key, value in pairs(data) do
entity[key] = value
end
TriggerClientEvent("community_bridge:client:UpdateEntity", -1, id, data)
return true
end
function ServerEntity.RegisterBehavior(id, behavior)
Behaviors.Create(id, behavior)
end
-- Clean up entities associated with a stopped resource
AddEventHandler('onResourceStop', function(resourceName)
local toDelete = {}
for id, entity in pairs(Entities) do
if entity.resource == resourceName then
table.insert(toDelete, id)
end
end
for _, id in pairs(toDelete) do
ServerEntity.Delete(id)
if Invoked[resourceName] then
ServerEntity.DestroyBulk(Invoked[resourceName])
Invoked[resourceName] = nil
end
end)
AddEventHandler('community_bridge:Server:OnPlayerLoaded', function(source)
-- print("Player loaded:", source)
TriggerClientEvent("community_bridge:client:CreateEntities", source, Entities)
end)
return ServerEntity
return ServerEntity
-49
View File
@@ -1,49 +0,0 @@
local Actions = {}
Action = {}
if not IsDuplicityVersion() then goto client end
function Action.Fire(id, players, ...)
local action = Actions[id]
if not action then return end
if type(players) == "table" then
for _, player in ipairs(players) do
TriggerClientEvent(GetCurrentResourceName() .. "client:Action", tonumber(player), id, ...)
end
return
end
TriggerClientEvent(GetCurrentResourceName() .. "client:Action", tonumber(players or -1), id, ...)
end
if IsDuplicityVersion() then return Actions end
::client::
function Action.Create(id, action)
assert(type(id) == "string", "id must be a string")
assert(type(action) == "function", "action must be a function")
Actions[id] = action
end
function Action.Remove(id)
Actions[id] = nil
end
function Action.Get(id)
return Actions[id]
end
function Action.GetAll()
return Actions
end
RegisterNetEvent(GetCurrentResourceName() .. "client:Action", function(id, ...)
local action = Actions[id]
if not action then return end
action(...)
end)
exports("Action", Action)
return Action
+121
View File
@@ -0,0 +1,121 @@
Behaviors = {
All = {},
isSetup = false,
invoked = {}
}
Behaviors.init = {
"anim",
"attach",
'clothing',
'follow',
'particles',
'scenarios',
'shop',
'stash',
'targets',
'weapon'
}
function Behaviors.Init()
if Behaviors.isSetup then return end
Behaviors.isSetup = true
for k, v in pairs(Behaviors.init) do
Require(string.format("lib/entities/shared/behaviors/%s.lua", v))
end
end
function Behaviors.Create(behaviorId, behavior)
if not behaviorId or not behavior then return end
Behaviors.All = Behaviors.All or {}
local invoking = GetInvokingResource() or "community_bridge"
Behaviors.All[invoking] = Behaviors.All[invoking] or {}
Behaviors.All[invoking][behaviorId] = behavior
end
function Behaviors.Get(behaviorId)
local invoking = GetInvokingResource() or "community_bridge"
return Behaviors.All[invoking] and Behaviors.All[invoking][behaviorId]
end
function Behaviors.Remove(behaviorId)
local invoking = GetInvokingResource() or "community_bridge"
if not Behaviors.All[invoking] or not Behaviors.All[invoking][behaviorId] then return end
Behaviors.All[invoking][behaviorId] = nil
return true
end
function Behaviors.Trigger(actionName, clientEntityData, ...)
if not clientEntityData or not actionName then return end
local invoking = clientEntityData.invoked or GetInvokingResource() or "community_bridge"
for property, behavior in pairs(Behaviors.All[invoking] or {}) do
local hasBehaviorArgs = Behaviors.Has(property, clientEntityData) -- this is everything that's contained inside the object's individual property
if hasBehaviorArgs and behavior[actionName] then
local success, result = pcall(behavior[actionName], clientEntityData, hasBehaviorArgs, ...)
if not success then
print(string.format("[ClientEntity] Behavior %s failed: %s", property, result))
end
end
end
for property, behavior in pairs(Behaviors.All['community_bridge'] or {}) do
local hasBehaviorArgs = Behaviors.Has(property, clientEntityData) -- this is everything that's contained inside the object's individual property
if hasBehaviorArgs and behavior[actionName] and not Behaviors.All[invoking]?[actionName] then
local success, result = pcall(behavior[actionName], clientEntityData, hasBehaviorArgs, ...)
if not success then
print(string.format("[ClientEntity] Behavior %s failed: %s", property, result))
end
end
end
end
function Behaviors.Inherit(behaviorId, clientEntityData, defaultData)
local invoking = GetInvokingResource() or "community_bridge"
if not Behaviors.All[invoking] or not Behaviors.All[invoking][behaviorId] then
print(string.format("[ClientEntity] Behavior %s does not exist", behaviorId))
return false
end
if not clientEntityData or not clientEntityData.id then
print("[ClientEntity] Invalid client entity data provided for inheritance")
return false
end
clientEntityData[behaviorId] = defaultData or {} -- Mark the entity as having this behavior
return true
end
function Behaviors.Has(behaviorId, clientEntityData)
return clientEntityData and clientEntityData[behaviorId]
end
function Behaviors.Cleanup(resourceName)
if not resourceName or not Behaviors.All[resourceName] then return end
for _, behaviorId in ipairs(Behaviors.All[resourceName]) do
Behaviors.Remove(behaviorId)
end
Behaviors.All[resourceName] = nil
end
AddEventHandler("onResourceStop", function(resourceName)
Behaviors.Cleanup(resourceName)
if resourceName ~= GetCurrentResourceName() then return end
for invoking, behaviors in pairs(Behaviors.All) do
for behaviorId, _ in pairs(behaviors) do
Behaviors.Remove(behaviorId)
end
end
end)
if IsDuplicityVersion() then
RegisterNetEvent("onResourceStart", function(resourceName)
if resourceName ~= GetCurrentResourceName() then return end
Wait(500)
Behaviors.Init()
end)
else
RegisterNetEvent("onClientResourceStart", function(resource)
if resource ~= GetCurrentResourceName() then return end
Wait(500)
Behaviors.Init()
end)
end
return Behaviors
+62
View File
@@ -0,0 +1,62 @@
if IsDuplicityVersion() then return end
local Animation = {
property = "anim",
default = {
flags = 49,
duration = -1
}
}
-- Anim.Play(id, entity, animDict, animName, blendIn, blendOut, duration, flag, playbackRate, onComplete)
function Animation.Play(entityData)
if entityData.entityType ~= "ped" then return end
local entity = entityData.spawned
if not entity then return end
local dict = entityData.anim?.dict
local name = entityData.anim?.name
local onComplete = entityData.anim?.onComplete and function() entityData.anim.onComplete(entityData) end
if not dict or not name then return end
local flags = entityData.anim.flags or Animation.default.flags
local duration = entityData.anim.duration or Animation.default.duration
entityData.anim.id = Bridge.Anim.Play(nil, entity, dict, name, 8.0, -8.0, duration, flags, 0.0, onComplete)
Bridge.Entity.Set(entityData.id, "anim", entityData.anim)
entityData.oldAnim = entityData.anim
Bridge.Entity.Set(entityData.id, "oldAnim", entityData.oldAnim)
-- SetTimeout(1000, function()
-- if entityData.anim then
-- entityData.anim.disable = false
-- Bridge.Entity.Set(entityData.id, "anim", entityData.anim)
-- end
-- end)
end
function Animation.OnSpawn(entityData)
print("Spawning animation for entity:", entityData.id)
if not entityData.spawned or not entityData.anim then return end
Animation.Play(entityData)
entityData.anim.disable = false
TaskSetBlockingOfNonTemporaryEvents(entityData.spawned, true)
SetBlockingOfNonTemporaryEvents(entityData.spawned, true)
Bridge.Entity.Set(entityData.id, "anim", entityData.anim)
end
function Animation.OnRemove(entityData)
if not entityData.spawned or not entityData.anim then return end
entityData.oldAnim = nil
entityData.anim.disable = true
Bridge.Entity.Set(entityData.id, "anim", entityData.anim)
Bridge.Entity.Set(entityData.id, "oldAnim", entityData.oldAnim)
end
function Animation.OnUpdate(entityData)
if not entityData.spawned or not entityData.anim then return end
if entityData.anim.disable then return end
if not IsEntityPlayingAnim(entityData.spawned, entityData.anim.dict, entityData.anim.name, 3) then
Bridge.Anim.Stop(entityData.anim?.id)
ClearPedTasksImmediately(entityData.spawned)
Wait(100)
Animation.Play(entityData)
end
end
Bridge.Entity.RegisterBehavior("anim", Animation)
return Animation
+52
View File
@@ -0,0 +1,52 @@
if IsDuplicityVersion() then return end
local Attach = {
property = "attach",
default = {
bone = 0,
offset = vector3(0.0, 0.0, 0.0),
rotation = vector3(0.0, 0.0, 0.0)
}
}
function Attach.OnSpawn(entityData)
if not entityData.spawned or not entityData.attach then return end
local entity = entityData.spawned
local targetEntity = entityData.attach.target
if type(targetEntity) == "string" then
targetEntity = Bridge.Entity.Get(targetEntity)?.spawned or targetEntity
else
local player = GetPlayerFromServerId(targetEntity)
if player and player ~= -1 then
targetEntity = GetPlayerPed(player)
end
end
targetEntity = tonumber(targetEntity)
if not targetEntity then return end
local bone = entityData.attach.bone or Attach.default.bone
local offset = entityData.attach.offset or Attach.default.offset
local rotation = entityData.attach.rotation or Attach.default.rotation
AttachEntityToEntity(entity, targetEntity, GetPedBoneIndex(targetEntity, bone), offset.x, offset.y, offset.z, rotation.x, rotation.y, rotation.z, true, true, false, true, 1, true)
Bridge.Entity.Set(entityData.id, "attach", entityData.attach)
end
function Attach.Detach(entityData)
if not entityData.spawned or not IsEntityAttached(entityData.spawned) then return end
DetachEntity(entityData.spawned, true, true)
Bridge.Entity.Set(entityData.id, "attach", entityData.attach)
end
function Attach.OnUpdate(entityData)
if not entityData.spawned then return end
if entityData.attach.disable then
return Attach.Detach(entityData)
end
local entity = entityData.spawned
local coords = GetEntityCoords(entity)
Bridge.Entity.Set(entityData.id, "coords", vector3(coords.x, coords.y, coords.z))
if IsEntityAttached(entity) then return end
Attach.OnSpawn(entityData)
end
Bridge.Entity.RegisterBehavior("attach", Attach)
return Attach
@@ -0,0 +1,82 @@
if IsDuplicityVersion() then return end
local Clothing = {
property = "clothing",
default = {
components = {},
props = {}
}
}
function Clothing.ChangeClothes(entityData)
if entityData.entityType ~= "ped" then return end
local entity = entityData.spawned
if not entity or not DoesEntityExist(entity) then return end
local clothing = entityData.clothing.target
if clothing then
if type(clothing) == "number" then
local player = GetPlayerFromServerId(clothing)
if player and player ~= -1 then
clothing = Bridge.Clothing.GetAppearance(GetPlayerPed(player))
end
elseif type(clothing) == "string" then
local targetEntityData = Bridge.Entity.Get(clothing)
if targetEntityData then
clothing = Bridge.Clothing.GetAppearance(targetEntityData.spawned)
end
end
else
clothing = entityData.clothing
end
Bridge.Clothing.SetAppearance(entity, clothing)
Bridge.Entity.Set(entityData.id, "clothing", clothing)
entityData.oldClothing = clothing
Bridge.Entity.Set(entityData.id, "oldClothing", clothing)
end
function Clothing.OnSpawn(entityData)
if not entityData.spawned or not entityData.clothing then return end
Clothing.ChangeClothes(entityData)
entityData.clothing.updating = false
end
function Clothing.OnRemove(entityData)
if not entityData.spawned or not entityData.clothing then return end
entityData.oldClothing = nil
entityData.clothing.updating = true
end
function Clothing.OnUpdate(entityData)
if not entityData.spawned or not entityData.clothing then return end
if entityData.clothing.updating then return end
entityData.clothing.updating = true
if not entityData.oldClothing then
Clothing.ChangeClothes(entityData)
return
end
for componentId, component in pairs(entityData.clothing.components or {}) do
local oldComponent = entityData.oldClothing.components and entityData.oldClothing.components[componentId]
if not oldComponent or oldComponent.drawable ~= component.drawable or oldComponent.texture ~= component.texture then
Clothing.ChangeClothes(entityData)
return
end
end
for propId, prop in pairs(entityData.clothing.props or {}) do
local oldProp = entityData.oldClothing.props and entityData.oldClothing.props[propId]
if not oldProp or oldProp.drawable ~= prop.drawable or oldProp.texture ~= prop.texture then
Clothing.ChangeClothes(entityData)
return
end
end
SetTimeout(1000, function()
if entityData.clothing then
entityData.clothing.updating = false
Bridge.Entity.Set(entityData.id, "clothing", entityData.clothing)
end
end)
end
Bridge.Entity.RegisterBehavior("clothing", Clothing)
return Clothing
+75
View File
@@ -0,0 +1,75 @@
if IsDuplicityVersion() then return end
local Follow = {
All = {},
property = "follow",
default = {
speed = 1.0,
distance = 2.0
}
}
function Follow.PedWalkToPos(entityData)
if not entityData?.follow?.target or entityData?.entityType ~= "ped" then return end
local entity = entityData.spawned
local targetCoords = entityData.follow.target
if not targetCoords then return end
if type(targetCoords) == "number" then
local player = GetPlayerFromServerId(targetCoords)
if player and player ~= -1 then
targetCoords = GetEntityCoords(GetPlayerPed(player))
else
targetCoords = GetEntityCoords(targetCoords)
end
elseif type(targetCoords) == "string" then
local targetEntityData = Bridge.Entity.Get(targetCoords)
if targetEntityData then
targetCoords = GetEntityCoords(targetEntityData.spawned)
end
end
local entityPos = GetEntityCoords(entity)
local distance = #(targetCoords - entityPos)
if distance > (entityData.follow.distance or Follow.default.distance) then
if entityData.anim then
entityData.anim.disable = true
Bridge.Entity.Set(entityData.id, "anim", entityData.anim)
end
if entityData.scenarios then
entityData.scenarios.disable = true
Bridge.Entity.Set(entityData.id, "scenarios", entityData.scenarios)
end
local speed = entityData.follow.speed or Follow.default.speed
local heading = GetHeadingFromVector_2d(targetCoords.x - entityPos.x, targetCoords.y - entityPos.y)
TaskGoStraightToCoord(entity, targetCoords.x, targetCoords.y, targetCoords.z, speed, -1, heading, 0.0)
entityData.coords = GetEntityCoords(entity)
entityData.follow.walking = true
Bridge.Entity.Set(entityData.id, "coords", entityData.coords - vector3(0,0,1))
Bridge.Entity.Set(entityData.id, "follow", entityData.follow)
if entityData.follow.OnExit then entityData.follow.OnExit(entityData) end
return false
end
if not entityData.follow.walking then return end
entityData.follow.walking = false
Bridge.Entity.Set(entityData.id, "follow", entityData.follow)
if entityData.anim then
entityData.anim.disable = false
Bridge.Entity.Set(entityData.id, "anim", entityData.anim)
end
if entityData.scenarios then
entityData.scenarios.disable = false
Bridge.Entity.Set(entityData.id, "scenarios", entityData.scenarios)
end
ClearPedTasks(entity)
if entityData.follow.OnEnter then entityData.follow.OnEnter(entityData) end
return true
end
function Follow.OnUpdate(entityData)
assert(entityData?.id, "Entity ID is required")
local entity = entityData.spawned
if not entity or not DoesEntityExist(entity) then return end
return Follow.PedWalkToPos(entityData)
end
Bridge.Entity.RegisterBehavior("follow", Follow)
return Follow
@@ -0,0 +1,80 @@
if IsDuplicityVersion() then return end
Utility = Utility or Bridge.Utility
local ParticlesBehaviors = {
property = "particles",
default = {
dict = "cut_exile3",
ptfx = "cs_ex3_wheel_spin",
offset = vector3(0, 0, 0),
rotation = vector3(0, 0, 0),
size = 1.0,
color = vector3(255, 255, 255),
loopLength = 5000,
}
}
function ParticlesBehaviors.Start(entityData)
for _, particleData in ipairs(entityData.particles) do
local position = vector3(entityData.coords.x, entityData.coords.y, entityData.coords.z)
local rotation = vector3(entityData.rotation.x, entityData.rotation.y, entityData.rotation.z)
position = position + (particleData.offset?.xyz or vector3(0, 0, 0))
rotation = rotation + (particleData.rotation?.xyz or vector3(0, 0, 0))
particleData.playing = Bridge.Particle.Play(
particleData.dict or ParticlesBehaviors.default.dict,
particleData.ptfx or ParticlesBehaviors.default.ptfx,
position,
rotation,
particleData.size or ParticlesBehaviors.default.size,
particleData.color or ParticlesBehaviors.default.color,
particleData.looped,
particleData.loopLength or ParticlesBehaviors.default.loopLength
)
end
end
function ParticlesBehaviors.OnSpawn(entityData)
if not entityData.particles then return end
if entityData.particles.dict then -- single particle
entityData.particles = {entityData.particles}
end
ParticlesBehaviors.Start(entityData)
end
function ParticlesBehaviors.OnRemove(entityData)
if not entityData.particles then return end
for _, particleData in ipairs(entityData.particles) do
if particleData.playing then
Bridge.Particle.Stop(particleData.playing)
particleData.playing = nil
end
end
end
function ParticlesBehaviors.OnMove(entityData)
if not entityData.particles then return end
for _, particleData in ipairs(entityData.particles) do
if particleData.playing then
Particle.Stop(particleData.playing)
particleData.playing = nil
local position = vector3(entityData.coords.x, entityData.coords.y, entityData.coords.z)
local rotation = vector3(entityData.rotation.x, entityData.rotation.y, entityData.rotation.z)
position = position + (particleData.offset?.xyz or vector3(0, 0, 0))
rotation = rotation + (particleData.rotation?.xyz or vector3(0, 0, 0))
particleData.playing = Bridge.Particle.Play(
particleData.dict or ParticlesBehaviors.default.dict,
particleData.ptfx or ParticlesBehaviors.default.ptfx,
position,
rotation,
particleData.size or ParticlesBehaviors.default.size,
particleData.color or ParticlesBehaviors.default.color,
particleData.looped,
particleData.loopLength or ParticlesBehaviors.default.loopLength
)
end
end
end
Bridge.Entity.RegisterBehavior("particles", ParticlesBehaviors)
return ParticlesBehaviors
@@ -0,0 +1,64 @@
if IsDuplicityVersion() then return end
local Scenarios = {
property = "scenarios",
default = {
introClip = true,
duration = -1
}
}
-- scenarios.Play(id, entity, scenariosDict, scenariosName, blendIn, blendOut, duration, flag, playbackRate, onComplete)
function Scenarios.Play(entityData)
if entityData.entityType ~= "ped" then return end
local entity = entityData.spawned
if not entity then return end
local name = entityData.scenarios?.name
if not name then return end
local duration = entityData.scenarios?.duration or Scenarios.default.duration
local introClip = entityData.scenarios?.introClip or Scenarios.default.introClip
TaskStartScenarioInPlace(entity, name, duration, introClip)
if duration < 0 then return end
SetTimeout(duration, function()
if not entityData.scenarios then return end
ClearPedTasks(entity)
if not entityData.scenarios.onComplete then return end
entityData.scenarios.disabled = true
Bridge.Entity.Set(entityData.id, "scenarios", entityData.scenarios)
entityData.scenarios.onComplete(entityData)
end)
end
function Scenarios.OnSpawn(entityData)
if not entityData.spawned or not entityData.scenarios then return end
Scenarios.Play(entityData)
end
function Scenarios.OnRemove(entityData)
if not entityData.spawned or not entityData.scenarios then return end
ClearPedTasks(entityData.spawned)
end
function Scenarios.OnUpdate(entityData)
if not entityData.spawned or not entityData.scenarios then return end
if entityData.scenarios.disable then return end
if IsPedUsingScenario(entityData.spawned, entityData.scenarios.name) then return end
local entities = GetGamePool('CObject')
for _, obj in ipairs(entities or {}) do
obj = tonumber(obj)
local entityCoords = GetEntityCoords(obj)
local coords = vector3(entityData.coords.x, entityData.coords.y, entityData.coords.z)
if entityCoords then
local distance = #(entityCoords - coords)
if distance < 2.0 then
SetEntityAsMissionEntity(obj, false, false)
DeleteObject(obj)
break
end
end
end
Scenarios.Play(entityData)
end
Bridge.Entity.RegisterBehavior("scenarios", Scenarios)
return Scenarios
+58
View File
@@ -0,0 +1,58 @@
local Shop = {
property = "shop",
default = {
label = "Default Shop Label",
items = {
{item = "water", price = 10}
},
target = {
label = "Open Shop",
icon = "fa-solid fa-box"
}
}
}
function Shop.OnCreate(entityData)
local shop = entityData.shop
if not shop then return end
if IsDuplicityVersion() then
local label = shop.label or Shop.default.label
local items = shop.items or Shop.default.items
local coords = entityData.coords
local groups = shop.groups
Bridge.Inventory.RegisterShop(label, items, nil, groups)
return
end
entityData.targets = entityData.targets or {}
print(json.encode(entityData.targets))
table.insert(entityData.targets,
{
label = shop.target.label or "Shop",
icon = shop.target.icon or "fa-solid fa-box",
onSelect = function()
TriggerServerEvent("community_bridge:server:OpenShop", entityData.id)
end
}
)
end
if not IsDuplicityVersion() then return Bridge.Entity.RegisterBehavior("shop", Shop) end
RegisterNetEvent("community_bridge:server:OpenShop", function(id)
local src = source
if not src then return end
local entityData = Bridge.Entity.Get(id)
if not entityData or not entityData.shop then
return print(string.format("[Shop] OpenShop: Entity %s does not exist or has no shop", id))
end
local coords = entityData.coords
if not coords then return end
local distance = #(GetEntityCoords(GetPlayerPed(src)) - coords)
if distance > 3.0 then
return print(string.format("[Shop] OpenShop: Player %s is too far from entity %s", src, id))
end
Bridge.Inventory.OpenShop(src, id)
end)
return Shop
+61
View File
@@ -0,0 +1,61 @@
local Stash = {
property = "stash",
default = {
label = "default_stash_label",
slots = 20,
maxWeight = 100000,
target = {
label = "Open Stash",
icon = "fa-solid fa-box",
}
}
}
function Stash.OnCreate(entityData)
if not entityData.stash then return end
if IsDuplicityVersion() then
local label = entityData.stash.label or Stash.default.label
local slots = entityData.stash.slots or Stash.default.slots
local weight = entityData.stash.maxWeight or Stash.default.maxWeight
local owner = entityData.stash.owner
local groups = entityData.stash.groups
Bridge.Inventory.RegisterStash(entityData.id, label, slots, weight, owner, groups)
return
end
entityData.targets = entityData.targets or {}
entityData.targets['stash'] = {
label = entityData.stash.target.label or Stash.default.target.label,
icon = entityData.stash.target.icon or Stash.default.target.icon,
description = entityData.stash.target.description,
groups = entityData.stash.target.groups,
canInteract = function(_)
local entData = Bridge.Entity.Get(entityData.id)
return not entData.stash.disable
end,
onSelect = function()
TriggerServerEvent("community_bridge:server:OpenStash", entityData.id)
end
}
Bridge.Entity.Set(entityData.id, 'targets', entityData.targets)
end
if not IsDuplicityVersion() then return Bridge.Entity.RegisterBehavior("stash", Stash) end
RegisterNetEvent("community_bridge:server:OpenStash", function(id)
local src = source
if not src then return end
local entityData = Bridge.Entity.Get(id)
if not entityData or not entityData.stash then
return print(string.format("[Stash] OpenStash: Entity %s does not exist or has no stash", id))
end
local coords = vector3(entityData.coords.x, entityData.coords.y, entityData.coords.z)
if not coords then return end
local distance = #(GetEntityCoords(GetPlayerPed(src)) - coords)
if distance > 3.0 then
return print(string.format("[Stash] OpenStash: Player %s is too far from entity %s", src, id))
end
Bridge.Inventory.OpenStash(src, "stash", id)
end)
Bridge.Entity.RegisterBehavior("stash", Stash)
+78
View File
@@ -0,0 +1,78 @@
if IsDuplicityVersion() then return end
local Targets = {
property = "targets",
default = {
label = "Default Target Label",
distance = 2,
size = vector3(2.0, 2.0, 2.0),
}
}
function Targets.OnSpawn(entityData)
if not entityData.targets then return end
if entityData.targets?.label then
local temp = entityData.targets
entityData.targets = {temp}
end
print("Spawned targets:", entityData.targets)
local numberedTargets = {}
for k, v in pairs(entityData.targets) do
local onSelect = v.onSelect
if onSelect then
v.onSelect = function(entity)
onSelect(entityData, entity)
end
end
table.insert(numberedTargets, v)
end
table.sort(numberedTargets, function(a, b) return (a.label < b.label) end)
if not entityData.spawned then
local size = Targets.default.size
Bridge.Target.AddBoxZone(entityData.id, entityData.coords, entityData.size, entityData.heading, numberedTargets, entityData.debug)
else
Bridge.Target.AddLocalEntity(entityData.spawned, numberedTargets)
end
entityData.oldTargets = entityData.targets
Bridge.Entity.Set(entityData.id, "oldTargets", entityData.oldTargets)
end
function Targets.OnRemove(entityData)
if not entityData.oldTargets then return end
if not entityData.spawned then
return Bridge.Target.RemoveZone(entityData.id)
end
Bridge.Target.RemoveLocalEntity(entityData.spawned)
end
function Targets.OnUpdate(entityData)
if not entityData.oldTargets then return end
local doesntMatch = false
for k, v in pairs(entityData.targets) do
if not entityData.oldTargets or not entityData.oldTargets[k] then
doesntMatch = true
break
end
local old = entityData.oldTargets[k]
if old.label ~= v.label
or old.distance ~= v.distance
or old.description ~= v.description
then
doesntMatch = true
break
end
end
for k, v in pairs(entityData.oldTargets) do
if not entityData.targets or not entityData.targets[k] then
doesntMatch = true
break
end
end
if doesntMatch then
Targets.OnRemove(entityData)
Wait(100)
Targets.OnSpawn(entityData)
end
end
Bridge.Entity.RegisterBehavior("targets", Targets)
return Targets
+54
View File
@@ -0,0 +1,54 @@
if IsDuplicityVersion() then return end
local Weapon = {
property = "weapon",
default = {
name = "WEAPON_UNARMED",
ammo = 0
}
}
function Weapon.GiveWeapon(entityData)
if entityData.entityType ~= "ped" then return end
local entity = entityData.spawned
if not entity or not DoesEntityExist(entity) then return end
if entityData.weapon?.name then
local ammo = entityData.weapon.ammo or 0
local hash = GetHashKey(entityData.weapon.name)
GiveWeaponToPed(entity, hash, ammo, false, true)
TaskSwapWeapon(entity, true)
end
entityData.oldWeapon = entityData.weapon
Bridge.Entity.Set(entityData.id, "oldWeapon", entityData.oldWeapon)
end
function Weapon.OnSpawn(entityData)
if not entityData.spawned or not entityData.weapon then return end
Weapon.GiveWeapon(entityData)
entityData.weapon.updating = false
end
function Weapon.OnRemove(entityData)
if not entityData.spawned or not entityData.weapon then return end
entityData.oldWeapon = nil
entityData.weapon.updating = true
end
function Weapon.OnUpdate(entityData)
if not entityData.spawned or not entityData.weapon then return end
if entityData.weapon.updating then return end
entityData.weapon.updating = true
if not entityData.oldWeapon or entityData.oldWeapon.name ~= entityData.weapon.name then
Weapon.GiveWeapon(entityData)
end
SetTimeout(1000, function()
if entityData.weapon then
entityData.weapon.updating = false
Bridge.Entity.Set(entityData.id, "weapon", entityData.weapon)
end
end)
Bridge.Entity.Set(entityData.id, "weapon", entityData.weapon)
end
Bridge.Entity.RegisterBehavior("weapon", Weapon)
return Weapon
-117
View File
@@ -1,117 +0,0 @@
ItemsBuilder = ItemsBuilder or {}
ItemsBuilder = {}
---This will generate the items in the formats of qb_core, qb_core_old and ox_inventory. It will then build a lua file in the generateditems folder of the community_bridge.
---@param invoking string
---@param itemsTable table
ItemsBuilder.Generate = function(invoking, outputPrefix, itemsTable, useQB)
if not itemsTable then return end
invoking = invoking or GetInvokingResource() or GetCurrentResourceName() or "community_bridge"
local resourcePath = string.format("%s/%s/", GetResourcePath(invoking), outputPrefix or "generated_items")
-- remove any doubles slashes after initial double slash
-- resourcePath = resourcePath:gsub("//", "/")
-- check if directory exists
local folder = io.open(resourcePath, "r")
if not folder then
local createDirectoryCMD = string.format("if not exist \"%s\" mkdir \"%s\"", resourcePath, resourcePath)
local returned, err = io.popen(createDirectoryCMD)
if not returned then
print("🌮 Failed to create directory: ", err)
return
end
returned:close()
print("🌮 Created Directory: ", resourcePath)
else
folder:close()
end
local qbOld = {}
local qbNew = {}
local oxInventory = {}
if useQB then
for key, item in pairs(itemsTable) do
qbOld[key] = string.format(
"['%s'] = {name = '%s', label = '%s', weight = %s, type = 'item', image = '%s', unique = %s, useable = %s, shouldClose = %s, description = '%s'},",
key, key, item.label, item.weight, item.image or key .. 'png', item.unique, item.useable, item.shouldClose, item.description
)
qbNew[key] = string.format(
"['%s'] = {['name'] = '%s', ['label'] = '%s', ['weight'] = %s, ['type'] = 'item',['image'] = '%s', ['unique'] = %s, ['useable'] = %s, ['shouldClose'] = %s, ['description'] = '%s'},",
key, key, item.label, item.weight, item.image or key .. 'png', item.unique, item.useable, item.shouldClose, item.description
)
imagewithoutpng = item?.image and item.image:gsub(".png", "")
shouldRenderImage = imagewithoutpng and imagewithoutpng ~= key
oxInventory[key] = string.format(
[[
["%s"] = {
label = "%s",
description = "%s",
weight = %s,
stack = %s,
close = %s,
%s
}, ]],
key, item.label, item.description, item.weight, not item.unique, item.shouldClose,
shouldRenderImage and item.image and string.format([[client = {
image = '%s'
}]], item.image) or ""
)
end
else
for key, item in pairs(itemsTable) do
-- ['peanut_butter'] = {['name'] = 'peanut_butter',['label'] = 'Peanut Butter',['weight'] = 1000,['type'] = 'item',['image'] = 'peanut_butter.png',['unique'] = false,['useable'] = false,['shouldClose'] = true,['combinable'] = nil,['description'] = 'A cooking ingredient'},
qbOld[key] = string.format(
"['%s'] = {name = '%s', label = '%s', weight = %s, type = 'item', image = '%s', unique = %s, useable = %s, shouldClose = %s, description = '%s'},",
key, key, item.label, item.weight, item?.client?.image or key .. 'png', not item.stack, true, item.close, item.description
)
qbNew[key] = string.format(
"['%s'] = {['name'] = '%s', ['label'] = '%s', ['weight'] = %s, ['type'] = 'item', ['image'] = '%s', ['unique'] = %s, ['useable'] = %s, ['shouldClose'] = %s, ['description'] = '%s'},",
key, key, item.label, item.weight, item?.client?.image or key .. 'png', not item.stack, true, item.close, item.description
)
imagewithoutpng = item?.client?.image and item.client.image:gsub(".png", "")
shouldRenderImage = imagewithoutpng and imagewithoutpng ~= key
oxInventory[key] = string.format(
[[
["%s"] = {
label = "%s",
description = "%s",
weight = %s,
stack = %s,
close = %s,
%s
}, ]],
key, item.label, item.description, item.weight, item.stack, item.close,
shouldRenderImage and item?.client?.image and string.format( [[client = {
image = '%s'
}]], item.client.image) or ""
)
end
end
local function write(fileName, content)
local filePath = resourcePath .. fileName
local file = io.open(filePath, "w")
if file then
for key, value in pairs(content) do
file:write(string.format("%s\n", value))
end
file:close()
print("🌮 Items File Created: " .. filePath)
else
print("🌮 Something Broke for: " .. filePath)
end
end
write(invoking.."(".."qb_core_old).lua", qbOld)
write(invoking.."(".."qb_core_new).lua", qbNew)
write(invoking.."(".."ox_inventory).lua", oxInventory)
end
exports('ItemsBuilder', ItemsBuilder)
return ItemsBuilder
-74
View File
@@ -1,74 +0,0 @@
LootTable = LootTable or {}
local lootTables = {}
LootTable.Register = function(name, items)
local repackedTable = {}
for k, v in pairs(items) do
table.insert(repackedTable, {
name = k,
min = v.min,
max = v.max,
chance = v.chance,
tier = v.tier,
item = v.item,
metadata = v.metadata
})
end
lootTables[name] = repackedTable
return lootTables[name]
end
LootTable.Get = function(name)
assert(name, "No Name Passed For Loot Table")
return lootTables[name] or {}
end
LootTable.GetRandomItem = function(name, tier, randomNumber)
assert(name, "No Name Passed For Loot Table")
if tier == nil then tier = 1 end
local lootTable = lootTables[name] or {}
math.randomseed(GetGameTimer())
local chance = randomNumber or math.random(1, 100)
for _, v in pairs(lootTable) do
if v.chance <= chance and tier == v.tier then
return { item = v.item, metadata = v.metadata, count = math.random(v.min, v.max), tier = v.tier, chance = v.chance}
end
end
end
LootTable.GetRandomItems = function(name, tier, randomNumber)
assert(name, "No Name Passed For Loot Table")
if tier == nil then tier = 1 end
local lootTable = LootTable.Get(name)
math.randomseed(GetGameTimer())
local chance = randomNumber or math.random(1, 100)
local items = {}
for _, v in pairs(lootTable) do
if v.chance <= chance and tier == v.tier then
table.insert(items,{item = v.item, metadata = v.metadata, count = math.random(v.min, v.max), tier = v.tier, chance = v.chance})
end
end
return items
end
LootTable.GetRandomItemsWithLimit = function(name, tier, randomNumber)
assert(name, "No Name Passed For Loot Table")
if tier == nil then tier = 1 end
local lootTable = LootTable.Get(name)
math.randomseed(GetGameTimer())
local chance = randomNumber or math.random(1, 100)
local items = {}
for k = #lootTable, 1, -1 do
local v = lootTable[k]
if chance <= v.chance and tier == v.tier then
table.insert(items, {v.item, v.metadata, math.random(v.min, v.max), v.tier, v.chance})
table.remove(lootTable, k)
end
end
return items
end
--
exports('LootTable', LootTable)
return LootTable
+14 -13
View File
@@ -39,14 +39,12 @@ end
cLib = {
Require = Require,
Callback = Callback or Require("lib/utility/shared/callbacks.lua"),
Callback = Callback or Require("lib/callback/shared/callback.lua"),
Ids = Ids or Require("lib/utility/shared/ids.lua"),
ReboundEntities = ReboundEntities or Require("lib/utility/shared/rebound_entities.lua"),
Tables = Tables or Require("lib/utility/shared/tables.lua"),
Tables = Table or Require("lib/utility/shared/tables.lua"),
Prints = Prints or Require("lib/utility/shared/prints.lua"),
Math = Math or Require("lib/utility/shared/math.lua"),
LA = LA or Require("lib/utility/shared/la.lua"),
Perlin = Perlin or Require("lib/utility/shared/perlin.lua"),
LA = LA or Require("lib/utility/shared/la.lua")
-- Zones = Poly or Require("lib/zones/shared/zones.lua"),
-- Action = Action or Require("lib/entities/shared/actions.lua"),
}
@@ -57,13 +55,15 @@ if not IsDuplicityVersion() then goto client end
cLib.SQL = SQL or Require("lib/sql/server/sqlHandler.lua")
cLib.Logs = Logs or Require("lib/logs/server/logs.lua")
cLib.ItemsBuilder = ItemsBuilder or Require("lib/generators/server/ItemsBuilder.lua")
cLib.LootTables = LootTables or Require("lib/generators/server/lootTables.lua")
cLib.Cache = Cache or Require("lib/cache/shared/cache.lua")
cLib.ServerEntity = ServerEntity or Require("lib/entities/server/server_entity.lua")
cLib.Marker = Marker or Require("lib/markers/server/server.lua")
cLib.Particle = Particle or Require("lib/particles/server/particles.lua")
cLib.Shell = Shells or Require("lib/shells/server/shells.lua")
cLib.Entity = ServerEntity or Require("lib/entities/server/server_entity.lua")
-- Depricated
cLib.ServerEntity = cLib.Entity
if IsDuplicityVersion() then return cLib end
::client::
@@ -72,16 +72,17 @@ cLib.Placeable = Placeable or Require("lib/placers/client/object_placer.lua")
cLib.Utility = Utility or Require("lib/utility/client/utility.lua")
cLib.PlaceableObject = ObjectPlacer or Require("lib/placers/client/placeable_object.lua")
cLib.Raycast = Raycast or Require("lib/raycast/client/raycast.lua")
cLib.Point = Point or Require("lib/points/client/pointsv2.lua")
cLib.Point = Point or Require("lib/points/client/points.lua")
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")
cLib.ClientStateBag = ClientStateBag or Require("lib/statebags/client/client.lua")
cLib.Marker = Marker or Require("lib/markers/client/markers.lua")
cLib.Anim = Anim or Require("lib/anim/client/client.lua")
cLib.Cutscene = Cutscene or Require("lib/cutscenes/client/cutscene.lua")
--cLib.DUI = DUI or Require("lib/dui/client/dui.lua")
cLib.Particle = Particle or Require("lib/particles/client/particles.lua")
cLib.Entity = ClientEntity or Require("lib/entities/client/client_entity.lua")
cLib.Vehicles = Vehicles or Require("lib/vehicles/client.lua")
-- Deprecated
cLib.ClientEntity = cLib.Entity
return cLib
+86 -98
View File
@@ -1,115 +1,103 @@
Logs = Logs or {}
local WebhookURL = "" -- Add webhook URL here if using built-in logging system
local LogoForEmbed = "https://cdn.discordapp.com/avatars/299410129982455808/31ce635662206e8bd0132c34ce9ce683?size=1024"
local LogSystem = "built-in" -- Default log system, can be "built-in", "qb", or "ox_lib"
local BridgeServerConfig = BridgeServerConfig or Require('settings/serverConfig.lua')
---This will send a log to the configured webhook or log system.
---@param src number
---@param message string
---@return nil
Logs.Send = function(src, message)
if not src or not message then return end
local logType = LogSystem or "built-in"
if logType == "built-in" then
PerformHttpRequest(WebhookURL, function(err, text, headers) end, 'POST', json.encode(
{
username = "Community_Bridge's Logger",
avatar_url = 'https://avatars.githubusercontent.com/u/192999457?s=400&u=da632e8f64c85def390cfd1a73c3b664d6882b38&v=4',
embeds = {
{
color = "15769093",
title = GetCurrentResourceName(),
url = 'https://discord.gg/Gm6rYEXUsn',
thumbnail = { url = LogoForEmbed },
fields = {
{
name = '**Player ID**',
value = src,
inline = true,
},
{
name = '**Player Identifier**',
value = Framework.GetPlayerIdentifier(src),
inline = true,
},
{
name = 'Log Message',
value = "```"..message.."```",
inline = false,
},
},
timestamp = os.date('!%Y-%m-%dT%H:%M:%S'),
footer = {
text = "Community_Bridge | ",
icon_url = 'https://avatars.githubusercontent.com/u/192999457?s=400&u=da632e8f64c85def390cfd1a73c3b664d6882b38&v=4',
},
}
}
}), { ['Content-Type']= 'application/json' })
elseif logType == "qb" then
return TriggerEvent('qb-log:server:CreateLog', GetCurrentResourceName(), GetCurrentResourceName(), 'green', message)
elseif logType == "ox_lib" then
return lib.logger(src, GetCurrentResourceName(), message)
local pendingLogs = {}
local sendTimer = nil
local function sendBufferedLogsToDiscord()
if #pendingLogs == 0 then
sendTimer = nil
return
end
end
local embeds = {}
Logs.Notify = function(src, url, image, message)
if not src or not message then return end
local logType = LogSystem or "built-in"
if logType == "built-in" then
embeds[url] = embeds[url] or {}
local embed = embeds[url].embed or {}
local firstName, lastName = Framework.GetPlayerName(src)
table.insert(embed, {
color = "15769093",
title = GetInvokingResource(),
-- url = 'https://discord.gg/Gm6rYEXUsn',
thumbnail = { url = LogoForEmbed },
local embeds = {}
for _, log in ipairs(pendingLogs) do
table.insert(embeds, {
color = '15769093',
title = log.resource,
thumbnail = { url = BridgeServerConfig.EmbedLogo },
fields = {
{
name = '**Player ID**',
value = src,
inline = true,
},
{
name = '**Player Identifier**',
value = Framework.GetPlayerIdentifier(src),
inline = true,
},
{
name = 'Log Message',
value = "```"..message.."```",
value = '```' .. log.message .. '```',
inline = false,
},
},
timestamp = os.date('!%Y-%m-%dT%H:%M:%S'),
footer = {
text = "Community_Bridge | ",
icon_url = 'https://avatars.githubusercontent.com/u/192999457?s=400&u=da632e8f64c85def390cfd1a73c3b664d6882b38&v=4',
}
},
timestamp = log.timestamp,
})
embeds[url].embed = embed
if embeds[url].inProgress then return end
embeds[url].inProgress = true
SetTimeout(5000, function()
PerformHttpRequest(url, function(err, text, headers) end, 'POST', json.encode({
username = string.format("%s %s", firstName, lastName),
avatar_url = image or 'https://avatars.githubusercontent.com/u/192999457?s=400&u=da632e8f64c85def390cfd1a73c3b664d6882b38&v=4',
embeds = embeds[url].embed
}), { ['Content-Type']= 'application/json' })
embeds[url].inProgress = false
end)
elseif logType == "qb" then
return TriggerEvent('qb-log:server:CreateLog', GetCurrentResourceName(), GetCurrentResourceName(), 'green', message)
elseif logType == "ox_lib" then
return lib.logger(src, GetCurrentResourceName(), message)
end
PerformHttpRequest(BridgeServerConfig.WebhookURL, function(err, text, headers) end, 'POST', json.encode({
username = 'Community_Bridge Logger',
avatar_url = 'https://avatars.githubusercontent.com/u/192999457?s=400&u=da632e8f64c85def390cfd1a73c3b664d6882b38&v=4',
embeds = embeds
}), { ['Content-Type'] = 'application/json' })
pendingLogs = {}
sendTimer = nil
end
local function queueLogForDiscord(message)
table.insert(pendingLogs, {
message = tostring(message),
resource = GetInvokingResource() or GetCurrentResourceName(),
timestamp = os.date('!%Y-%m-%dT%H:%M:%S')
})
if not sendTimer then
sendTimer = true
SetTimeout(3000, sendBufferedLogsToDiscord)
end
end
local logHandlers = {
fivemerr = function(logData)
local fivemerrData = {
level = 'info',
message = tostring(logData),
resource = GetInvokingResource() or GetCurrentResourceName(),
}
PerformHttpRequest('https://api.fivemerr.com/v1/logs', function(code, text, headers)
if code ~= 200 then
print(('Failed to send log to Fivemerr API (HTTP %d): Please verify your API key is correct and the service is available.'):format(code))
end
end, 'POST', json.encode(fivemerrData), {
['Content-Type'] = 'application/json',
['Authorization'] = BridgeServerConfig.FivemerrApiKey
})
end,
qb = function(message)
TriggerEvent('qb-log:server:CreateLog', GetCurrentResourceName(), GetInvokingResource(), 'green', message, false)
end,
ox_lib = function(message)
lib.logger(GetInvokingResource(), GetCurrentResourceName(), message)
end,
['built-in'] = function(message)
queueLogForDiscord(message)
end
}
---@deprecated Use Logs.CreateLog instead (deprecated 9/1/25)
Logs.Send = function(src, message)
print('^1Deprecated^0 function Logs.Send called. Please use Logs.CreateLog instead.')
Logs.CreateLog(message)
end
---@deprecated Use Logs.CreateLog instead (deprecated 9/1/25)
Logs.Notify = function(src, url, image, message)
print('^1Deprecated^0 function Logs.Notify called. Please use Logs.CreateLog instead.')
Logs.CreateLog(message)
end
Logs.CreateLog = function(logData)
local handler = logHandlers[BridgeServerConfig.LogSystem]
if handler then handler(logData) end
end
exports('Logs', Logs)
return Logs
+47 -69
View File
@@ -1,7 +1,7 @@
Particles = {}
Particle = {}
---@diagnostic disable: duplicate-set-field
local Ids = Ids or Require("lib/utility/shared/ids.lua")
Ids = Ids or Require("lib/utility/shared/ids.lua")
local point = Require("lib/points/client/points.lua")
---Loads a ptfx asset into memory.
@@ -28,21 +28,58 @@ end
--- @param looped boolean
--- @param loopLength number|nil
--- @return number|nil ptfxHandle -- The handle of the particle effect, or nil if it failed to create.
function Particle.Play(dict, ptfx, pos, rot, scale, color, looped, loopLength)
function Particle.Play(dict, ptfx, pos, rot, scale, color, looped, removeAfter)
LoadPtfxAsset(dict)
UseParticleFxAssetNextCall(dict)
SetParticleFxNonLoopedColour(color.x, color.y, color.z)
local particle = nil
removeAfter = removeAfter or 5000
if looped then
particle = StartParticleFxLoopedAtCoord(ptfx, pos.x, pos.y, pos.z, rot.x, rot.y, rot.z, scale, false, false, false, false)
CreateThread(function()
if loopLength then
Wait(loopLength)
Particle.Remove(particle)
local strParticle = tostring(particle)
Particles[strParticle] = particle
Wait(10)
if particle == 0 or not DoesParticleFxLoopedExist(particle) then
particle = StartParticleFxNonLoopedAtCoord(ptfx, pos.x, pos.y, pos.z, rot.x, rot.y, rot.z, scale, false, false, false, false)
if not particle and particle == 0 then
print(string.format("[Particle] Failed to start particle fx: %s from dict: %s", ptfx, dict))
return nil
end
end)
else
particle = StartParticleFxNonLoopedAtCoord(ptfx, pos.x, pos.y, pos.z, rot.x, rot.y, rot.z, scale, false, false, false, false)
local strParticle = tostring(particle)
Particles[strParticle] = particle
CreateThread(function()
while Particles[strParticle] do
Wait(removeAfter)
if not Particles[strParticle] then break end
RemoveParticleFx(particle, false)
particle = StartParticleFxNonLoopedAtCoord(ptfx, pos.x, pos.y, pos.z, rot.x, rot.y, rot.z, scale, false, false, false, false)
Particles[strParticle] = particle
end
end)
return strParticle
else
if not removeAfter or removeAfter <= 0 then return particle end
CreateThread(function()
while Particles[strParticle] do
Wait(removeAfter)
if not Particles[strParticle] then break end
StopParticleFxLooped(particle, false)
UseParticleFxAssetNextCall(dict)
LoadPtfxAsset(dict)
particle = StartParticleFxLoopedAtCoord(ptfx, pos.x, pos.y, pos.z, rot.x, rot.y, rot.z, scale, false, false, false, false)
Particles[strParticle] = particle
end
end)
return strParticle
end
else
particle = StartParticleFxLoopedAtCoord(ptfx, pos.x, pos.y, pos.z, rot.x, rot.y, rot.z, scale, false, false, false, false)
Wait(10)
if not DoesParticleFxLoopedExist(particle) then
particle = StartParticleFxNonLoopedAtCoord(ptfx, pos.x, pos.y, pos.z, rot.x, rot.y, rot.z, scale, false, false, false, false)
end
Wait(removeAfter)
Particle.Stop(particle)
end
return particle
@@ -53,66 +90,7 @@ function Particle.Stop(particle)
StopParticleFxLooped(particle, false)
RemoveParticleFx(particle, false)
RemoveNamedPtfxAsset(particle)
end
function Particle.Create(data)
assert(data, "Particle data is nil")
assert(data.dict, "Invalid particle data. Must contain string dict.")
assert(data.ptfx, "Invalid particle data. Must contain string ptfx.")
local _id = data.id or Ids.CreateUniqueId(Particles)
data = {
id = _id,
dict = data.dict,
ptfx = data.ptfx,
position = data.position or vector3(0.0, 0.0, 0.0),
rotation = data.rotation or vector3(0, 0, 0),
size = data.size or 1.0,
color = data.color or vector3(255, 255, 255),
looped = data.looped or false,
loopLength = data.loopLength or nil,
spawned = false,
}
Particles[_id] = data
point.Register( -- checking if players in range
_id,
data.position,
data.drawDistance or 50.0,
data,
function(_)
if not Particles[_id] then return point.Remove(_id) end
local particleData = Particles[_id]
if particleData.spawned then return end
particleData.spawned = Particle.Play(
particleData.dict,
particleData.ptfx,
particleData.position,
particleData.rotation,
particleData.size,
particleData.color,
particleData.looped,
particleData.loopLength
)
end,
function(markerData)
if not Particles[_id] then return end
local particleData = Particles[_id]
if not particleData.spawned then return end
Particle.Stop(particleData.spawned)
particleData.spawned = nil
end
)
return _id
end
function Particle.Remove(id)
if not id then return end
local particle = Particles[id]
if not particle then return end
Particle.Stop(particle.spawned)
Particles[id] = nil
point.Remove(id)
Particles[tostring(particle)] = nil
end
+129 -238
View File
@@ -1,255 +1,146 @@
-- -- Grid-based point system
-- Point = {}
-- local ActivePoints = {}
-- local GridCells = {}
-- local LoopStarted = false
-- local insidePoints = {}
-- local data = {} -- 👈 Move this outside the function
-- -- Grid configuration
-- local GRID_SIZE = 500.0 -- Size of each grid cell
-- local CELL_BUFFER = 1 -- Number of adjacent cells to check
local GRIDE_SIZE_X = 8968.83 / 2
local GRIDE_SIZE_Y = 126200.40 / 2
local CELL_SIZE = 500
-- -- Consider adding these optimizations
-- local ADAPTIVE_WAIT = false -- Adjust wait time based on player speed
local Grid = {}
Grid.Generated = false
local Grids = {}
Point = {}
Point.All = {}
-- ---This is an internal function, do not call this externally
-- function Point.GetCellKey(coords)
-- local cellX = math.floor(coords.x / GRID_SIZE)
-- local cellY = math.floor(coords.y / GRID_SIZE)
-- return cellX .. ":" .. cellY
-- end
function Grid.Generate()
if Grid.Generated then return end
Grid.Generated = true
local numOfCellsX = math.ceil(GRIDE_SIZE_X / CELL_SIZE)
local numOfCellsY = math.ceil(GRIDE_SIZE_Y / CELL_SIZE)
-- ---This is an internal function, do not call this externally
-- function Point.RegisterInGrid(point)
-- local cellKey = Point.GetCellKey(point.coords)
for x = -numOfCellsX, numOfCellsX do
Grids[x] = {}
for y = -numOfCellsY, numOfCellsY do
Grids[x][y] = {}
end
end
end
-- -- Initialize cell if it doesn't exist
-- GridCells[cellKey] = GridCells[cellKey] or {
-- points = {},
-- count = 0
-- }
function Grid.GetCellId(coords)
local cellX = math.floor(coords.x / CELL_SIZE) + 1
local cellY = math.floor(coords.y / CELL_SIZE) + 1
return string.format("%d_%d", cellX, cellY)
end
-- -- Add point to cell
-- GridCells[cellKey].points[point.id] = point
-- GridCells[cellKey].count = GridCells[cellKey].count + 1
function Grid.GetCellByCoords(coords)
local cellX = math.floor(coords.x / CELL_SIZE) + 1
local cellY = math.floor(coords.y / CELL_SIZE) + 1
return Grids[cellX][cellY]
end
-- -- Store cell reference in point
-- point.cellKey = cellKey
-- end
local Points = {}
Points.Started = false
function Point.StartLoop()
if Points.Started then return end
Points.Started = true
-- ---This is an internal function, do not call this externally
-- function Point.UpdateInGrid(point, oldCellKey)
-- -- Remove from old cell if cell key changed
-- if oldCellKey and oldCellKey ~= point.cellKey then
-- if GridCells[oldCellKey] and GridCells[oldCellKey].points[point.id] then
-- GridCells[oldCellKey].points[point.id] = nil
-- GridCells[oldCellKey].count = GridCells[oldCellKey].count - 1
CreateThread(function()
while Points.Started do
local playerPed = PlayerPedId()
if playerPed ~= -1 then
local coords = GetEntityCoords(playerPed)
local cell = Grid.GetCellByCoords(coords)
for _, point in pairs(cell or {}) do
if point.isEntity then
local entity = point.target
if DoesEntityExist(entity) then
local entityCoords = GetEntityCoords(entity)
local distance = #(coords - entityCoords)
if distance < point.distance then
if not point.inside then
point.inside = true
point.args = point?.onEnter(point, point.args) or point.args
end
elseif point.inside then
point.inside = false
point.args = point?.onExit(point, point.args) or point.args
end
end
else
local distance = #(vector3(coords.x, coords.y, coords.z) - vector3(point.coords.x, point.coords.y, point.coords.z))
if distance < point.distance then
if not point.inside then
point.inside = true
point.args = point?.onEnter(point, point.args) or point.args
end
elseif point.inside then
point.inside = false
point.args = point?.onExit(point, point.args) or point.args
end
end
if point.inside and point.onUpdate then
point.onUpdate(point, point.args)
end
end
end
Wait(1000)
end
end)
end
-- -- Clean up empty cells
-- if GridCells[oldCellKey].count <= 0 then
-- GridCells[oldCellKey] = nil
-- end
-- end
function Point.Register(id, target, distance, args, _onEnter, _onExit, _onUpdate)
local isEntity = type(target) == "number"
local coords = isEntity and GetEntityCoords(target) or target
Grid.Generate()
local self = args or {}
self.id = id
self.target = target -- Store entity ID or Vector3
self.isEntity = isEntity
self.coords = coords
self.distance = distance
self.onEnter = _onEnter or function() end
self.onExit = _onExit or function() end
self.onUpdate = _onUpdate or function() end
self.inside = false -- Track if player is inside
local grid = Grid.GetCellByCoords(coords)
grid[id] = self
Point.All[id] = self
Point.StartLoop()
return self
end
-- -- Add to new cell
-- Point.RegisterInGrid(point)
-- end
-- end
function Point.Remove(id)
local point = Point.All[id]
if not point then return false end
-- ---Gets nearby cells based on the coords
-- ---@param coords table
-- ---@return table
-- function Point.GetNearbyCells(coords)
-- local cellX = math.floor(coords.x / GRID_SIZE)
-- local cellY = math.floor(coords.y / GRID_SIZE)
-- local nearbyCells = {}
-- Remove from grid
local grid = Grid.GetCellByCoords(point.coords)
if grid then
grid[point.id] = nil
end
-- -- Get current and adjacent cells
-- for x = cellX - CELL_BUFFER, cellX + CELL_BUFFER do
-- for y = cellY - CELL_BUFFER, cellY + CELL_BUFFER do
-- local key = x .. ":" .. y
-- if GridCells[key] then
-- table.insert(nearbyCells, key)
-- end
-- end
-- end
Point.All[id] = nil
return true
end
-- return nearbyCells
-- end
function Point.Get(id)
return Point.All[id]
end
-- ---Returns all points in the same cell as the given point
-- ---This will require you to pass the point object
-- ---@param point table
-- ---@return table
-- function Point.CheckPointsInSameCell(point)
-- local cellKey = point.cellKey
-- if not GridCells[cellKey] then return {} end
function Point.UpdateCoords(id, coords)
local point = Point.All[id]
if not point then return end
-- local nearbyPoints = {}
-- for id, otherPoint in pairs(GridCells[cellKey].points) do
-- if id ~= point.id then
-- local distance = #(point.coords - otherPoint.coords)
-- if distance < (point.distance + otherPoint.distance) then
-- nearbyPoints[id] = otherPoint
-- end
-- end
-- end
local newGrid = Grid.GetCellByCoords(coords)
if not newGrid or newGrid[point.id] then return end
local oldGrid = Grid.GetCellByCoords(point.coords)
if oldGrid then
oldGrid[point.id] = nil
end
point.coords = coords
newGrid[point.id] = point
return true
end
-- return nearbyPoints
-- end
function Point.GetAll()
return Point.All
end
-- ---Internal function that starts the loop. Do not call this function directly.
-- function Point.StartLoop()
-- if LoopStarted then return false end
-- LoopStarted = true
-- -- Remove the "local data = {}" line from here
-- CreateThread(function()
-- while LoopStarted do
-- local playerPed = PlayerPedId()
-- while playerPed == -1 do
-- Wait(100)
-- playerPed = PlayerPedId()
-- end
-- local playerCoords = GetEntityCoords(playerPed)
-- local targetsExist = false
-- local playerCellKey = Point.GetCellKey(playerCoords)
-- local nearbyCells = Point.GetNearbyCells(playerCoords)
-- local playerSpeed = GetEntitySpeed(playerPed)
-- local maxWeight = 1000
-- local waitTime = ADAPTIVE_WAIT and math.max(maxWeight/10, maxWeight - playerSpeed * maxWeight/10) or maxWeight
-- -- Process only points in nearby cells
-- for _, cellKey in ipairs(nearbyCells) do
-- if GridCells[cellKey] then
-- for id, point in pairs(GridCells[cellKey].points) do
-- targetsExist = true
-- -- Update entity position if needed
-- local oldCellKey = point.cellKey
-- if point.isEntity then
-- point.coords = GetEntityCoords(point.target)
-- point.cellKey = Point.GetCellKey(point.coords)
-- Point.UpdateInGrid(point, oldCellKey)
-- end
-- local coords = point.coords and vector3(point.coords.x, point.coords.y, point.coords.z) or vector3(0, 0, 0)
-- local distance = #(playerCoords - coords)
-- --local distance = #(playerCoords - point.coords)
-- -- Check if player entered/exited the point
-- if distance < point.distance then
-- if not point.inside then
-- point.inside = true
-- data[point.id] = data[point.id] or point.args or {}
-- data[point.id] = point.onEnter(point, data[point.id])
-- insidePoints[point.id] = point
-- end
-- -- Modified main loop exit handler
-- elseif point.inside then
-- point.inside = false
-- data[point.id] = data[point.id] or point.args or {}
-- local result = point.onExit(point, data[point.id])
-- data[point.id] = result ~= nil and result or data[point.id] -- ← Use consistent fallback
-- point.args = data[point.id] -- ← Update point.args to match data[point.id]
-- insidePoints[point.id] = nil
-- end
-- -- if point.onNearby then
-- -- point.onNearby(GridCells[cellKey]?.points, waitTime)
-- -- end
-- end
-- end
-- end
-- for id, insidepoint in pairs(insidePoints) do
-- local pos = insidepoint.coords and vector3(insidepoint.coords.x, insidepoint.coords.y, insidepoint.coords.z) or vector3(0, 0, 0)
-- local dist = #(playerCoords - pos)
-- if dist > insidepoint.distance then
-- insidepoint.inside = false
-- data[insidepoint.id] = data[insidepoint.id] or insidepoint.args or {}
-- local result = insidepoint.onExit(insidepoint, data[insidepoint.id])
-- data[insidepoint.id] = result ~= nil and result or data[insidepoint.id]
-- insidepoint.args = data[insidepoint.id] -- ← Keep data in sync
-- insidePoints[insidepoint.id] = nil
-- end
-- end
-- Wait(waitTime) -- Faster updates when moving quickly
-- end
-- end)
-- return true
-- end
-- ---Create a point based on a vector or entityID
-- ---@param id string
-- ---@param target number || vector3
-- ---@param distance number
-- ---@param _onEnter function
-- ---@param _onExit function
-- ---@param _onNearby function
-- ---@param data self
-- ---@return table
-- function Point.Register(id, target, distance, args, _onEnter, _onExit, _onNearby)
-- local isEntity = type(target) == "number"
-- local coords = isEntity and GetEntityCoords(target) or target
-- local self = {}
-- self.id = id
-- self.target = target -- Store entity ID or Vector3
-- self.isEntity = isEntity
-- self.coords = coords
-- self.distance = distance
-- self.onEnter = _onEnter or function() end
-- self.onExit = _onExit or function() end
-- self.onNearby = _onNearby or function() end
-- self.inside = false -- Track if player is inside
-- self.args = args or {}
-- ActivePoints[id] = self
-- Point.RegisterInGrid(self)
-- Point.StartLoop()
-- return self
-- end
-- ---Remove an exsisting point by its id
-- ---@param id string
-- function Point.Remove(id)
-- local point = ActivePoints[id]
-- if point then
-- local cellKey = point.cellKey
-- if GridCells[cellKey] and GridCells[cellKey].points[id] then
-- GridCells[cellKey].points[id] = nil
-- GridCells[cellKey].count = GridCells[cellKey].count - 1
-- if GridCells[cellKey].count <= 0 then
-- GridCells[cellKey] = nil
-- end
-- end
-- ActivePoints[id] = nil
-- end
-- end
-- ---Returnes a point by its id
-- ---@param id string
-- ---@return table
-- function Point.Get(id)
-- return ActivePoints[id]
-- end
-- function Point.UpdateCoords(id, coords)
-- local point = ActivePoints[id]
-- if point then
-- point.coords = coords
-- local oldCellKey = point.cellKey
-- point.cellKey = Point.GetCellKey(coords)
-- Point.UpdateInGrid(point, oldCellKey)
-- end
-- end
-- ---Returns all points
-- ---@return table
-- function Point.GetAll()
-- return ActivePoints
-- end
-- return Point
return Point
-143
View File
@@ -1,143 +0,0 @@
local GRIDE_SIZE_X = 8968.83 / 2
local GRIDE_SIZE_Y = 126200.40 / 2
local CELL_SIZE = 500
local Grid = {}
Grid.Generated = false
local Grids = {}
Point = {}
Point.All = {}
function Grid.Generate()
if Grid.Generated then return end
Grid.Generated = true
local numOfCellsX = math.ceil(GRIDE_SIZE_X / CELL_SIZE)
local numOfCellsY = math.ceil(GRIDE_SIZE_Y / CELL_SIZE)
for x = -numOfCellsX, numOfCellsX do
Grids[x] = {}
for y = -numOfCellsY, numOfCellsY do
Grids[x][y] = {}
end
end
end
function Grid.GetCellId(coords)
local cellX = math.floor(coords.x / CELL_SIZE) + 1
local cellY = math.floor(coords.y / CELL_SIZE) + 1
return string.format("%d_%d", cellX, cellY)
end
function Grid.GetCellByCoords(coords)
local cellX = math.floor(coords.x / CELL_SIZE) + 1
local cellY = math.floor(coords.y / CELL_SIZE) + 1
return Grids[cellX][cellY]
end
local Points = {}
Points.Started = false
function Point.StartLoop()
if Points.Started then return end
Points.Started = true
CreateThread(function()
while Points.Started do
local playerPed = PlayerPedId()
if playerPed ~= -1 then
local coords = GetEntityCoords(playerPed)
local cell = Grid.GetCellByCoords(coords)
for _, point in pairs(cell or {}) do
if point.isEntity then
local entity = point.target
if DoesEntityExist(entity) then
local entityCoords = GetEntityCoords(entity)
local distance = #(coords - entityCoords)
if distance < point.distance then
if not point.inside then
point.inside = true
point.args = point?.onEnter(point, point.args) or point.args
end
elseif point.inside then
point.inside = false
point.args = point?.onExit(point, point.args) or point.args
end
end
else
local distance = #(vector3(coords.x, coords.y, coords.z) - vector3(point.coords.x, point.coords.y, point.coords.z))
if distance < point.distance then
if not point.inside then
point.inside = true
point.args = point?.onEnter(point, point.args) or point.args
end
elseif point.inside then
point.inside = false
point.args = point?.onExit(point, point.args) or point.args
end
end
end
end
Wait(1000)
end
end)
end
function Point.Register(id, target, distance, args, _onEnter, _onExit)
local isEntity = type(target) == "number"
local coords = isEntity and GetEntityCoords(target) or target
Grid.Generate()
local self = {}
self.id = id
self.target = target -- Store entity ID or Vector3
self.isEntity = isEntity
self.coords = coords
self.distance = distance
self.onEnter = _onEnter or function() end
self.onExit = _onExit or function() end
self.inside = false -- Track if player is inside
self.args = args or {}
local grid = Grid.GetCellByCoords(coords)
grid[id] = self
Point.All[id] = self
Point.StartLoop()
return self
end
function Point.Remove(id)
local point = Point.All[id]
if not point then return false end
-- Remove from grid
local grid = Grid.GetCellByCoords(point.coords)
if grid then
grid[point.id] = nil
end
Point.All[id] = nil
return true
end
function Point.Get(id)
return Point.All[id]
end
function Point.UpdateCoords(id, coords)
local point = Point.All[id]
if not point then return end
local newGrid = Grid.GetCellByCoords(coords)
if not newGrid or newGrid[point.id] then return end
local oldGrid = Grid.GetCellByCoords(point.coords)
if oldGrid then
oldGrid[point.id] = nil
end
point.coords = coords
newGrid[point.id] = point
return true
end
function Point.GetAll()
return Point.All
end
return Point
-48
View File
@@ -1,48 +0,0 @@
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 ("player:%s"):format(GetPlayerServerId(PlayerId())) or nil,
function(bagName, key, value, lastValue, replicated)
local actualPlayerId = getPlayerFromStateBagName(bagName)
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
return callback(tonumber(actualPlayerId), key, value, lastValue, replicated)
end
end)
end
return ClientStateBag
View File
Whitespace-only changes.
+40 -12
View File
@@ -3,7 +3,7 @@ local blipIDs = {}
local spawnedPeds = {}
Locales = Locales or Require('modules/locales/shared.lua')
Point = Point or Require('lib/points/client/pointsv2.lua')
Point = Point or Require('lib/points/client/points.lua')
---Get the hash of a model (string or number)
---@param model string|number
@@ -131,6 +131,19 @@ function Utility.CreateBlip(coords, sprite, color, scale, label, shortRange, dis
return blip
end
function Utility.CreateRadiusBlip(coords, radius, color, alpha, label, shortRange, displayType)
local blip = AddBlipForRadius(coords.x, coords.y, coords.z, radius)
SetBlipColour(blip, color or 3)
SetBlipAlpha(blip, alpha or 255)
SetBlipDisplay(blip, displayType or 2)
SetBlipAsShortRange(blip, shortRange)
AddTextEntry(label, label)
BeginTextCommandSetBlipName(label)
EndTextCommandSetBlipName(blip)
blipIDs[tostring(blip)] = blip
return blip
end
---Create a blip on the provided entity
---@param entity number
---@param sprite number
@@ -291,18 +304,33 @@ end
---@param scale number
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)
SetTextFont(4)
SetTextProportional(true)
SetTextColour(255, 255, 255, 215)
SetTextEntry("STRING")
SetTextCentre(true)
AddTextComponentString(text)
DrawText(x, y)
local factor = (string.len(text)) / 370
DrawRect(x, y + 0.0125, 0.015 + factor, 0.03, 41, 11, 41, 100)
if not onScreen then return end
local lineCount = 0
local maxLineLen = 0
for line in string.gmatch(text, "[^\n]+") do
lineCount = lineCount + 1
maxLineLen = math.max(maxLineLen, string.len(line))
end
local widthFactor = maxLineLen * 0.012 * scale
local height = 0.06 * scale * lineCount
-- Set text properties
SetTextScale(scale or 0.35, scale or 0.35)
SetTextFont(4)
SetTextProportional(true)
SetTextColour(255, 255, 255, 215)
SetTextEntry("STRING")
SetTextCentre(true)
AddTextComponentString(text)
DrawText(x, y)
-- Draw background rectangle
DrawRect(x, y + height / 2, widthFactor + 0.015 + 0.006, height + 0.015 + 0.006, 10, 25, 47, 200)
DrawRect(x, y + height / 2, widthFactor + 0.015, height + 0.015, 17, 45, 78, 50)
end
function Utility.Draw3DHelpTextExt(coords, text, scale)
end
---Show a native notification
+61
View File
@@ -1,5 +1,66 @@
Math = Math or {}
---@class Math
---@field public name string @add name field to class Car, you'll see it in code completion
Math = {}
--- Rounds a number to the nearest whole number.
---@param value number: The value to round.
---@return number: The rounded value.
function Math.Round(value)
return math.floor(value + 0.5)
end
function Math.Truncate(value, decimals)
local mul = decimals and (10 ^ decimals) or 1
if value < 0 then
return math.ceil(value * mul) / mul
else
return math.floor(value * mul) / mul
end
end
--- Warps the number around from max to min and vice versa.
---@param value number: The value to wrap.
---@param min number: The minimum value.
---@param max number: The maximum value.
---@return number: The wrapped value.
function Math.Wrap(value, min, max)
local range = max - min
return (value - min) % range + min
end
--- Gets an interpolated value between two numbers.
---@see https://en.wikipedia.org/wiki/Smoothstep
---@param value number The interpolation value.
---@param min number : The minimum value.
---@param max number : The maximum value.
---@return number The interpolated value.
function Math.Smooth(value, min, max)
value = Math.Clamp((value - min) / (max - min), 0, 1)
return value * value * (3 - 2 * value)
end
--- Gets the nearest whole number.
--- @param value number The value to round.
--- @return number The rounded value.
function Math.Nearest(value)
return math.floor(value + 0.5)
end
--- Maps a value from one range to another.
---@param value number The value to map.
---@param inMin number The minimum value for the provided value.
---@param inMax number The maximum value for the provided value.
---@param outMin number The minimum value for the output.
---@param outMax number The maximum value for the output.
function Math.Map(value, inMin, inMax, outMin, outMax)
return (value - inMin) / (inMax - inMin) * (outMax - outMin) + outMin
end
function Math.Clamp(value, min, max)
return math.min(math.max(value, min), max)
end
-110
View File
@@ -1,110 +0,0 @@
local Perlin = {}
-- Permutation table for random gradients
local perm = {}
local grad3 = {
{1,1,0}, {-1,1,0}, {1,-1,0}, {-1,-1,0},
{1,0,1}, {-1,0,1}, {1,0,-1}, {-1,0,-1},
{0,1,1}, {0,-1,1}, {0,1,-1}, {0,-1,-1}
}
-- Initialize permutation table
local function ShufflePermutation()
local p = {}
for i = 0, 255 do
p[i] = i
end
for i = 255, 1, -1 do
local j = math.random(i + 1) - 1
p[i], p[j] = p[j], p[i]
end
for i = 0, 255 do
perm[i] = p[i]
perm[i + 256] = p[i] -- Repeat for wrapping
end
end
ShufflePermutation() -- Randomize on load
-- Dot product helper
local function Dot(g, x, y, z)
return g[1] * x + g[2] * y + (z and g[3] * z or 0)
end
-- Fade function (smootherstep)
local function Fade(t)
return t * t * t * (t * (t * 6 - 15) + 10)
end
-- Linear interpolation
local function Lerp(a, b, t)
return a + (b - a) * t
end
-- **Perlin Noise 1D**
function Perlin.Noise1D(x)
local X = math.floor(x) & 255
x = x - math.floor(x)
local u = Fade(x)
local a = perm[X]
local b = perm[X + 1]
return Lerp(a, b, u) * (2 / 255) - 1
end
-- **Perlin Noise 2D**
function Perlin.Noise2D(x, y)
local X = math.floor(x) & 255
local Y = math.floor(y) & 255
x, y = x - math.floor(x), y - math.floor(y)
local u, v = Fade(x), Fade(y)
local aa = perm[X] + Y
local ab = perm[X] + Y + 1
local ba = perm[X + 1] + Y
local bb = perm[X + 1] + Y + 1
return Lerp(
Lerp(Dot(grad3[perm[aa] % 12 + 1], x, y), Dot(grad3[perm[ba] % 12 + 1], x - 1, y), u),
Lerp(Dot(grad3[perm[ab] % 12 + 1], x, y - 1), Dot(grad3[perm[bb] % 12 + 1], x - 1, y - 1), u),
v
)
end
-- **Perlin Noise 3D**
function Perlin.Noise3D(x, y, z)
local X = math.floor(x) & 255
local Y = math.floor(y) & 255
local Z = math.floor(z) & 255
x, y, z = x - math.floor(x), y - math.floor(y), z - math.floor(z)
local u, v, w = Fade(x), Fade(y), Fade(z)
local aaa = perm[X] + Y + Z
local aba = perm[X] + Y + Z + 1
local aab = perm[X] + Y + 1 + Z
local abb = perm[X] + Y + 1 + Z + 1
local baa = perm[X + 1] + Y + Z
local bba = perm[X + 1] + Y + Z + 1
local bab = perm[X + 1] + Y + 1 + Z
local bbb = perm[X + 1] + Y + 1 + Z + 1
return Lerp(
Lerp(
Lerp(Dot(grad3[perm[aaa] % 12 + 1], x, y, z), Dot(grad3[perm[baa] % 12 + 1], x - 1, y, z), u),
Lerp(Dot(grad3[perm[aab] % 12 + 1], x, y - 1, z), Dot(grad3[perm[bab] % 12 + 1], x - 1, y - 1, z), u),
v
),
Lerp(
Lerp(Dot(grad3[perm[aba] % 12 + 1], x, y, z - 1), Dot(grad3[perm[bba] % 12 + 1], x - 1, y, z - 1), u),
Lerp(Dot(grad3[perm[abb] % 12 + 1], x, y - 1, z - 1), Dot(grad3[perm[bbb] % 12 + 1], x - 1, y - 1, z - 1), u),
v
),
w
)
end
exports('Perlin', Perlin)
return Perlin
-324
View File
@@ -1,324 +0,0 @@
local Entities = {}
local isServer = IsDuplicityVersion()
local registeredFunctions = {}
ReboundEntities = {}
function ReboundEntities.AddFunction(func)
assert(func, "Func is nil")
table.insert(registeredFunctions, func)
return #registeredFunctions
end
function ReboundEntities.RemoveFunction(id)
assert(id and registeredFunctions[id], "Invalid ID")
registeredFunctions[id] = false
end
function FireFunctions(...)
for _, func in pairs(registeredFunctions) do
func(...)
end
end
function ReboundEntities.Register(entityData)
assert(entityData and entityData.position, "Invalid entity data")
entityData.id = entityData.id or Ids.CreateUniqueId(Entities)
entityData.isServer = isServer
setmetatable(entityData, { __tostring = function() return entityData.id end })
Entities[entityData.id] = entityData
FireFunctions(entityData)
return entityData
end
local function Unregister(id)
Entities[id] = nil
end
function ReboundEntities.GetSyncData(entityData, key)
return entityData[key]
end
function ReboundEntities.GetAll()
return Entities
end
function ReboundEntities.GetById(id)
return Entities[tostring(id)]
end
function ReboundEntities.GetByModel(model)
local entities = {}
for _, entity in pairs(Entities) do
if entity.model == model then
table.insert(entities, entity)
end
end
return entities
end
function ReboundEntities.GetClosest(pos)
local closest, closestDist = nil, 9999
for _, entity in pairs(Entities) do
local dist = #(pos - entity.position)
if dist < closestDist then
closest, closestDist = entity, dist
end
end
return closest
end
function ReboundEntities.GetWithinRadius(pos, radius)
local entities = {}
for _, entity in pairs(Entities) do
if #(pos - entity.position) < radius then
table.insert(entities, entity)
end
end
return entities
end
function ReboundEntities.SetOnSyncKeyChange(entityData, cb)
local data = ReboundEntities.GetById(entityData.id or entityData)
assert(data, "Entity not found")
data.onSyncKeyChange = cb
end
exports('ReboundEntities', ReboundEntities)
if not isServer then goto client end
function ReboundEntities.Create(entityData, src)
local entity = ReboundEntities.Register(entityData)
assert(entity and entity.position, "Invalid entity data")
entity.rotation = entity.rotation or vector3(0, 0, entityData.heading or 0)
TriggerClientEvent(GetCurrentResourceName() .. ":client:CreateReboundEntity", src or -1, entity)
return entity
end
function ReboundEntities.SetCheckRestricted(entityData, cb)
assert(type(cb) == "function", "Check restricted is not a function")
entityData.restricted = cb
end
function ReboundEntities.CheckRestricted(src, entityData)
return entityData.restricted and entityData.restricted(tonumber(src), entityData) or false
end
function ReboundEntities.Refresh(src)
TriggerClientEvent(GetCurrentResourceName() .. ":client:CreateReboundEntities", tonumber(src), ReboundEntities.GetAccessibleList(src))
end
function ReboundEntities.Delete(id)
Unregister(id)
TriggerClientEvent(GetCurrentResourceName() .. ":client:DeleteReboundEntity", -1, id)
end
function ReboundEntities.DeleteMultiple(entityDatas)
local ids = {}
for _, data in pairs(entityDatas) do
Unregister(data.id)
table.insert(ids, data.id)
end
TriggerClientEvent(GetCurrentResourceName() .. ":client:DeleteReboundEntities", -1, ids)
end
function ReboundEntities.CreateMultiple(entityDatas, src, restricted)
local _entityDatas = {}
for _, data in pairs(entityDatas) do
local entity = ReboundEntities.Register(data)
assert(entity and entity.position, "Invalid entity data")
entity.rotation = entity.rotation or vector3(0, 0, 0)
if restricted then ReboundEntities.SetCheckRestricted(entity, restricted) end
if not ReboundEntities.CheckRestricted(src, entity) then
_entityDatas[entity.id] = entity
end
end
TriggerClientEvent(GetCurrentResourceName() .. ":client:CreateReboundEntities", src or -1, _entityDatas)
return _entityDatas
end
function ReboundEntities.SetSyncData(entityData, key, value)
entityData[key] = value
if entityData.onSyncKeyChange then
entityData.onSyncKeyChange(entityData, key, value)
end
TriggerClientEvent(GetCurrentResourceName() .. ":client:SetReboundSyncData", -1, entityData.id, key, value)
end
function ReboundEntities.GetAccessibleList(src)
local list = {}
for _, data in pairs(ReboundEntities.GetAll()) do
if not ReboundEntities.CheckRestricted(src, data) then
list[data.id] = data
end
end
return list
end
RegisterNetEvent("playerJoining", function()
ReboundEntities.Refresh(source)
end)
AddEventHandler('onResourceStart', function(resource)
if resource ~= GetCurrentResourceName() then return end
Wait(1000)
for _, src in pairs(GetPlayers()) do
ReboundEntities.Refresh(src)
end
end)
::client::
if isServer then return ReboundEntities end
function ReboundEntities.LoadModel(model)
assert(model, "Model is nil")
model = type(model) == "number" and model or GetHashKey(model) -- Corrected to GetHashKey
RequestModel(model)
for i = 1, 100 do
if HasModelLoaded(model) then return model end
Wait(100)
end
error(string.format("Failed to load model %s", model))
end
function ReboundEntities.Spawn(entityData)
local model = entityData.model
local position = entityData.position
assert(position, "Position is nil")
local rotation = entityData.rotation or vector3(0, 0, 0)
local entity = model and CreateObject(ReboundEntities.LoadModel(model), position.x, position.y, position.z, false, false, false)
if entity then SetEntityRotation(entity, rotation.x, rotation.y, rotation.z) end
if entityData.onSpawn then entity = entityData.onSpawn(entityData, entity) or entity end
return entity, true
end
function ReboundEntities.SetOnSpawn(id, cb)
local entity = ReboundEntities.GetById(tostring(id))
assert(entity, "Entity not found")
entity.onSpawn = cb
return true
end
function ReboundEntities.Despawn(entityData)
local entity = entityData.entity
if entityData.onDespawn then entityData.onDespawn(entityData, entity) end
if entity and DoesEntityExist(entity) then DeleteEntity(entity) end
return nil, nil
end
function ReboundEntities.SetOnDespawn(id, cb)
local entity = ReboundEntities.GetById(tostring(id))
assert(entity, "Entity not found")
entity.onDespawn = cb
return true
end
local spawnLoopRunning = false
function ReboundEntities.SpawnLoop(distanceToCheck, waitTime)
if spawnLoopRunning then return end
spawnLoopRunning = true
distanceToCheck = distanceToCheck or 50
waitTime = waitTime or 2500
CreateThread(function()
while spawnLoopRunning do
for _, entity in pairs(Entities) do
local pos = GetEntityCoords(PlayerPedId())
local position = vector3(entity.position.x, entity.position.y, entity.position.z)
local dist = #(pos - position)
if dist <= distanceToCheck and not entity.entity then
entity.entity, entity.inRange = ReboundEntities.Spawn(entity)
elseif dist > distanceToCheck and entity.entity then
entity.entity, entity.inRange = ReboundEntities.Despawn(entity)
end
end
Wait(waitTime)
end
end)
end
function ReboundEntities.GetByEntity(entity)
for _, data in pairs(Entities) do
if data.entity == entity then return data end
end
end
function ReboundEntities.CreateClient(entityData)
local entity = ReboundEntities.Register(entityData)
if entity then ReboundEntities.SpawnLoop() end
return entity
end
function ReboundEntities.DeleteClient(id)
local entityData = ReboundEntities.GetById(tostring(id))
assert(not entityData.isServer, "Cannot delete server entity from client")
if entityData.entity then ReboundEntities.Despawn(entityData) end
Unregister(id)
return true
end
function ReboundEntities.CreateMultipleClient(entityDatas)
local _entityDatas = {}
for _, data in pairs(entityDatas) do
local entityData = ReboundEntities.CreateClient(data)
_entityDatas[entityData.id] = entityData
end
return _entityDatas
end
function ReboundEntities.DeleteMultipleClient(ids)
for _, id in pairs(ids) do
ReboundEntities.DeleteClient(id)
end
end
local function DeleteFromServer(id)
local entityData = ReboundEntities.GetById(tostring(id))
if entityData then
entityData.isServer = nil
ReboundEntities.DeleteClient(id)
end
end
local function DeleteMultipleFromServer(ids)
for _, id in pairs(ids) do
DeleteFromServer(id)
end
end
RegisterNetEvent(GetCurrentResourceName() .. ":client:CreateReboundEntity", function(entityData)
ReboundEntities.CreateClient(entityData)
end)
RegisterNetEvent(GetCurrentResourceName() .. ":client:DeleteReboundEntity", function(id)
DeleteFromServer(id)
end)
RegisterNetEvent(GetCurrentResourceName() .. ":client:CreateReboundEntities", function(entityDatas)
ReboundEntities.CreateMultipleClient(entityDatas)
end)
RegisterNetEvent(GetCurrentResourceName() .. ":client:DeleteReboundEntities", function(ids)
ReboundEntities.DeleteMultipleClient(ids)
end)
RegisterNetEvent(GetCurrentResourceName() .. ":client:SetReboundSyncData", function(id, key, value)
local entityData = ReboundEntities.GetById(id)
if not entityData then return end
entityData[key] = value
if entityData.onSyncKeyChange then
entityData.onSyncKeyChange(entityData, key, value)
end
end)
AddEventHandler('onResourceStop', function(resource)
if resource ~= GetCurrentResourceName() then return end
spawnLoopRunning = false
for _, entity in pairs(Entities) do
if entity.entity then DeleteEntity(tonumber(entity.entity)) end
end
end)
return ReboundEntities
@@ -1,45 +0,0 @@
local ReboundEntities = ReboundEntities or Require("lib/utility/shared/rebound_entities.lua") -- Fixed path
local Action = Action or Require("lib/entities/shared/actions.lua") -- Fixed path and name
local LA = LA or Require("lib/utility/shared/la.lua") -- Fixed path
REA = {}
if not IsDuplicityVersion() then goto client end
if IsDuplicityVersion() then return end
::client::
local ActionsInProgress = {}
Action.Create("LerpToPosition", function(reboundId, start, position, duration, shouldRepeat, overrideStartTime)
local re = ReboundEntities.GetById(reboundId) -- Use GetById
assert(re, "Rebound entity not found")
local entity = re and re.entity
if not entity or not DoesEntityExist(entity) then return end -- Check existence
local startTime = GetGameTimer()
local endTime = overrideStartTime or startTime + duration
ActionsInProgress[reboundId] = {reboundId, start, position, duration, shouldRepeat, startTime}
local t = 0
CreateThread(function()
while shouldRepeat or t < 1 do
-- Check if entity still exists
if not re.entity or not DoesEntityExist(re.entity) then
ActionsInProgress[reboundId] = nil
break
end
entity = re.entity -- Update entity handle in case it changed (unlikely but safe)
t = (GetGameTimer() - startTime) / duration
local lerpPosition = LA.LerpVector(start, position, t)
SetEntityCoordsNoOffset(entity, lerpPosition.x, lerpPosition.y, lerpPosition.z, false, false, false) -- Use NoOffset
Wait(0)
end
-- Set final position if not repeating
if not shouldRepeat and re.entity and DoesEntityExist(re.entity) then
SetEntityCoordsNoOffset(re.entity, position.x, position.y, position.z, false, false, false)
end
ActionsInProgress[reboundId] = nil -- Clear when done
end)
end)
+510
View File
@@ -0,0 +1,510 @@
---@diagnostic disable: duplicate-set-field
Vehicles = Vehicles or {}
-- Vehicle properties setter function
--
-- Inspired by and derived from vehicle property handlers in:
-- ESX Framework (https://github.com/esx-framework/esx_core) [License: GPLv3]
-- QBCore Framework (https://github.com/qbcore-framework/qb-core) [License: GPLv3]
--
-- Note: The ox_lib version (https://github.com/overextended/ox_lib) [License: LGPLv3] also draws heavily from these projects.
--
-- This code is licensed under the GNU General Public License v3.0 (GPLv3).
-- You may use, modify, and distribute this code under the terms of the GPLv3.
-- See LICENSE file for full details.
if not DecorIsRegisteredAsType("Player_Vehicle", 3) then DecorRegister("Player_Vehicle", 3) end
---@alias RGBColor number[] RGB color array [r, g, b] where each component is 0-255
---@alias VehicleExtras table<number, number> Vehicle extras where key is extra ID and value is state (0=enabled, 1=disabled)
---@class VehicleProperties
---@field model? number Vehicle model hash
---@field plate? string License plate text
---@field plateIndex? number License plate style index (0-5)
---@field bodyHealth? number Body health (0-1000)
---@field engineHealth? number Engine health (0-1000)
---@field tankHealth? number Tank health (0-1000)
---@field fuelLevel? number Fuel level (0-100)
---@field oilLevel? number Oil level (0-100)
---@field dirtLevel? number Dirt level (0-15)
---@field paintType1? number Primary paint type
---@field paintType2? number Secondary paint type
---@field color1? number|RGBColor Primary color (color index or RGB values)
---@field color2? number|RGBColor Secondary color (color index or RGB values)
---@field pearlescentColor? number Pearlescent color index
---@field interiorColor? number Interior color index
---@field dashboardColor? number Dashboard color index
---@field wheelColor? number Wheel color index
---@field wheelWidth? number Wheel width
---@field wheelSize? number Wheel size
---@field wheels? number Wheel type
---@field windowTint? number Window tint level (0-6)
---@field xenonColor? number Xenon headlight color
---@field neonEnabled? boolean[] Neon light states [left, right, front, back]
---@field neonColor? RGBColor Neon light color RGB values
---@field extras? VehicleExtras Vehicle extras configuration
---@field tyreSmokeColor? RGBColor Tyre smoke color RGB values
---@field modSpoilers? number Spoiler modification (-1 to max)
---@field modFrontBumper? number Front bumper modification (-1 to max)
---@field modRearBumper? number Rear bumper modification (-1 to max)
---@field modSideSkirt? number Side skirt modification (-1 to max)
---@field modExhaust? number Exhaust modification (-1 to max)
---@field modFrame? number Frame modification (-1 to max)
---@field modGrille? number Grille modification (-1 to max)
---@field modHood? number Hood modification (-1 to max)
---@field modFender? number Fender modification (-1 to max)
---@field modRightFender? number Right fender modification (-1 to max)
---@field modRoof? number Roof modification (-1 to max)
---@field modEngine? number Engine modification (-1 to max)
---@field modBrakes? number Brakes modification (-1 to max)
---@field modTransmission? number Transmission modification (-1 to max)
---@field modSuspension? number Suspension modification (-1 to max)
---@field modArmor? number Armor modification (-1 to max)
---@field modNitrous? number Nitrous modification (-1 to max)
---@field modHorns? number Horn modification (-1 to max)
---@field modSubwoofer? number Subwoofer modification (-1 to max)
---@field modTurbo? boolean Turbo toggle
---@field modSmokeEnabled? boolean Tyre smoke toggle
---@field modHydraulics? boolean Hydraulics toggle
---@field modXenon? boolean Xenon lights toggle
---@field modFrontWheels? number Front wheels modification (-1 to max)
---@field modBackWheels? number Back wheels modification (-1 to max)
---@field modCustomTiresF? boolean Custom front tires enabled
---@field modCustomTiresR? boolean Custom rear tires enabled
---@field modPlateHolder? number Plate holder modification (-1 to max)
---@field modVanityPlate? number Vanity plate modification (-1 to max)
---@field modTrimA? number Trim A modification (-1 to max)
---@field modOrnaments? number Ornaments modification (-1 to max)
---@field modDashboard? number Dashboard modification (-1 to max)
---@field modDial? number Dial modification (-1 to max)
---@field modDoorSpeaker? number Door speaker modification (-1 to max)
---@field modSeats? number Seats modification (-1 to max)
---@field modSteeringWheel? number Steering wheel modification (-1 to max)
---@field modShifterLeavers? number Shifter levers modification (-1 to max)
---@field modAPlate? number A-plate modification (-1 to max)
---@field modSpeakers? number Speakers modification (-1 to max)
---@field modTrunk? number Trunk modification (-1 to max)
---@field modHydrolic? number Hydraulic modification (-1 to max)
---@field modEngineBlock? number Engine block modification (-1 to max)
---@field modAirFilter? number Air filter modification (-1 to max)
---@field modStruts? number Struts modification (-1 to max)
---@field modArchCover? number Arch cover modification (-1 to max)
---@field modAerials? number Aerials modification (-1 to max)
---@field modTrimB? number Trim B modification (-1 to max)
---@field modTank? number Tank modification (-1 to max)
---@field modWindows? number Windows modification (-1 to max)
---@field modDoorR? number Door R modification (-1 to max)
---@field modLivery? number Livery modification (-1 to max)
---@field modLightbar? number Lightbar modification (-1 to max)
---@field modRoofLivery? number Roof livery modification (-1 to max)
---@field livery? number Vehicle livery (-1 to max)
---@field windows? number[] Array of damaged window indices
---@field doors? number[] Array of damaged door indices
---@field tyres? table<number, number> Map of tyre index to damage state (1=burst, 2=destroyed)
---@field bulletProofTyres? boolean Bulletproof tyres enabled
---@field driftTyres? boolean Drift tyres enabled
---@field doorLockStatus? number Door lock status (0=none, 1=unlocked, 2=locked, 3=lockout, 4=can't enter)
---@field brokenWheels? number|number[] Single wheel index or array of wheel indices to break off (0-7)
-- Handle state bag changes for vehicle properties
AddStateBagChangeHandler('community_bridge:SetVehicleProperties', '', function(bagName, _, value)
if not value or not GetEntityFromStateBagName then return end
-- Wait for entity to exist with timeout
local entity = nil
local attempts = 0
local maxAttempts = 100 -- 10 seconds at 100ms intervals
while not entity and attempts < maxAttempts do
local tempEntity = GetEntityFromStateBagName(bagName)
if tempEntity and tempEntity > 0 and DoesEntityExist(tempEntity) then
entity = tempEntity
break
end
attempts = attempts + 1
Wait(100)
end
if not entity then return end
-- Apply vehicle properties from state bag (prevents infinite loops)
Vehicles.SetVehicleProperties(entity, value, true)
Wait(500)
-- Clear state if we own the entity (prevents accumulation)
if NetworkGetEntityOwner(entity) == PlayerId() then
Vehicles.SetVehicleProperties(entity, value, true)
Entity(entity).state:set('community_bridge:SetVehicleProperties', nil, false)
end
end)
local gameBuild = GetGameBuildNumber()
---Get comprehensive vehicle properties
---@param vehicle number The vehicle entity handle
---@return VehicleProperties|nil properties Table containing all vehicle properties, or nil if vehicle doesn't exist
function Vehicles.GetVehicleProperties(vehicle)
if not DoesEntityExist(vehicle) then return end
local colorPrimary, colorSecondary = GetVehicleColours(vehicle)
local pearlescentColor, wheelColor = GetVehicleExtraColours(vehicle)
local paintType1 = GetVehicleModColor_1(vehicle)
local paintType2 = GetVehicleModColor_2(vehicle)
-- Handle custom colors (can be either number or table)
local primaryColor = colorPrimary --[[@as number|table]]
local secondaryColor = colorSecondary --[[@as number|table]]
if GetIsVehiclePrimaryColourCustom(vehicle) then
local r, g, b = GetVehicleCustomPrimaryColour(vehicle)
primaryColor = { r, g, b }
end
if GetIsVehicleSecondaryColourCustom(vehicle) then
local r, g, b = GetVehicleCustomSecondaryColour(vehicle)
secondaryColor = { r, g, b }
end
-- Get vehicle extras
local extras = {}
for i = 1, 15 do
if DoesExtraExist(vehicle, i) then
extras[i] = IsVehicleExtraTurnedOn(vehicle, i) and 0 or 1
end
end
-- Get vehicle damage information
local damage = {
windows = {},
doors = {},
tyres = {},
brokenWheels = {},
}
-- Check window damage
local windows = 0
for i = 0, 7 do
RollUpWindow(vehicle, i)
if not IsVehicleWindowIntact(vehicle, i) then
windows += 1
damage.windows[windows] = i
end
end
-- Check door damage
local doors = 0
for i = 0, 5 do
if IsVehicleDoorDamaged(vehicle, i) then
doors += 1
damage.doors[doors] = i
end
end
-- Check tyre damage
for i = 0, 7 do
if IsVehicleTyreBurst(vehicle, i, false) then
damage.tyres[i] = IsVehicleTyreBurst(vehicle, i, true) and 2 or 1
end
end
-- Check broken wheels
for i = 0, 7 do
if IsVehicleWheelBrokenOff(vehicle, i) then
table.insert(damage.brokenWheels, i)
end
end
-- Get neon light status
local neons = {}
for i = 0, 3 do
neons[i + 1] = IsVehicleNeonLightEnabled(vehicle, i)
end
return {
model = GetEntityModel(vehicle),
plate = GetVehicleNumberPlateText(vehicle),
plateIndex = GetVehicleNumberPlateTextIndex(vehicle),
bodyHealth = math.floor(GetVehicleBodyHealth(vehicle) + 0.5),
engineHealth = math.floor(GetVehicleEngineHealth(vehicle) + 0.5),
tankHealth = math.floor(GetVehiclePetrolTankHealth(vehicle) + 0.5),
fuelLevel = math.floor(GetVehicleFuelLevel(vehicle) + 0.5),
oilLevel = math.floor(GetVehicleOilLevel(vehicle) + 0.5),
dirtLevel = math.floor(GetVehicleDirtLevel(vehicle) + 0.5),
paintType1 = paintType1,
paintType2 = paintType2,
color1 = primaryColor,
color2 = secondaryColor,
pearlescentColor = pearlescentColor,
interiorColor = GetVehicleInteriorColor(vehicle),
dashboardColor = GetVehicleDashboardColour(vehicle),
wheelColor = wheelColor,
wheelWidth = GetVehicleWheelWidth(vehicle),
wheelSize = GetVehicleWheelSize(vehicle),
wheels = GetVehicleWheelType(vehicle),
windowTint = GetVehicleWindowTint(vehicle),
xenonColor = GetVehicleXenonLightsColor(vehicle),
neonEnabled = neons,
neonColor = { GetVehicleNeonLightsColour(vehicle) },
extras = extras,
tyreSmokeColor = { GetVehicleTyreSmokeColor(vehicle) },
modSpoilers = GetVehicleMod(vehicle, 0),
modFrontBumper = GetVehicleMod(vehicle, 1),
modRearBumper = GetVehicleMod(vehicle, 2),
modSideSkirt = GetVehicleMod(vehicle, 3),
modExhaust = GetVehicleMod(vehicle, 4),
modFrame = GetVehicleMod(vehicle, 5),
modGrille = GetVehicleMod(vehicle, 6),
modHood = GetVehicleMod(vehicle, 7),
modFender = GetVehicleMod(vehicle, 8),
modRightFender = GetVehicleMod(vehicle, 9),
modRoof = GetVehicleMod(vehicle, 10),
modEngine = GetVehicleMod(vehicle, 11),
modBrakes = GetVehicleMod(vehicle, 12),
modTransmission = GetVehicleMod(vehicle, 13),
modHorns = GetVehicleMod(vehicle, 14),
modSuspension = GetVehicleMod(vehicle, 15),
modArmor = GetVehicleMod(vehicle, 16),
modNitrous = GetVehicleMod(vehicle, 17),
modTurbo = IsToggleModOn(vehicle, 18),
modSubwoofer = GetVehicleMod(vehicle, 19),
modSmokeEnabled = IsToggleModOn(vehicle, 20),
modHydraulics = IsToggleModOn(vehicle, 21),
modXenon = IsToggleModOn(vehicle, 22),
modFrontWheels = GetVehicleMod(vehicle, 23),
modBackWheels = GetVehicleMod(vehicle, 24),
modCustomTiresF = GetVehicleModVariation(vehicle, 23),
modCustomTiresR = GetVehicleModVariation(vehicle, 24),
modPlateHolder = GetVehicleMod(vehicle, 25),
modVanityPlate = GetVehicleMod(vehicle, 26),
modTrimA = GetVehicleMod(vehicle, 27),
modOrnaments = GetVehicleMod(vehicle, 28),
modDashboard = GetVehicleMod(vehicle, 29),
modDial = GetVehicleMod(vehicle, 30),
modDoorSpeaker = GetVehicleMod(vehicle, 31),
modSeats = GetVehicleMod(vehicle, 32),
modSteeringWheel = GetVehicleMod(vehicle, 33),
modShifterLeavers = GetVehicleMod(vehicle, 34),
modAPlate = GetVehicleMod(vehicle, 35),
modSpeakers = GetVehicleMod(vehicle, 36),
modTrunk = GetVehicleMod(vehicle, 37),
modHydrolic = GetVehicleMod(vehicle, 38),
modEngineBlock = GetVehicleMod(vehicle, 39),
modAirFilter = GetVehicleMod(vehicle, 40),
modStruts = GetVehicleMod(vehicle, 41),
modArchCover = GetVehicleMod(vehicle, 42),
modAerials = GetVehicleMod(vehicle, 43),
modTrimB = GetVehicleMod(vehicle, 44),
modTank = GetVehicleMod(vehicle, 45),
modWindows = GetVehicleMod(vehicle, 46),
modDoorR = GetVehicleMod(vehicle, 47),
modLivery = GetVehicleMod(vehicle, 48),
modRoofLivery = GetVehicleRoofLivery(vehicle),
modLightbar = GetVehicleMod(vehicle, 49),
livery = GetVehicleLivery(vehicle),
windows = damage.windows,
doors = damage.doors,
tyres = damage.tyres,
brokenWheels = damage.brokenWheels,
bulletProofTyres = GetVehicleTyresCanBurst(vehicle),
driftTyres = gameBuild >= 2372 and GetDriftTyresEnabled(vehicle),
doorLockStatus = GetVehicleDoorLockStatus(vehicle),
}
end
---Apply vehicle properties to a vehicle
---@param vehicle number The vehicle entity handle
---@param props VehicleProperties Table containing vehicle properties to apply
---@param fromStateBag? boolean Internal flag to prevent infinite loops when called from state bag handler
function Vehicles.SetVehicleProperties(vehicle, props, fromStateBag)
if not DoesEntityExist(vehicle) then return false end
local colorPrimary, colorSecondary = GetVehicleColours(vehicle)
local pearlescentColor, wheelColor = GetVehicleExtraColours(vehicle)
SetVehicleModKit(vehicle, 0)
-- Apply vehicle extras
if props.extras then
for id, disable in pairs(props.extras) do
local extraId = tonumber(id)
if extraId then
SetVehicleExtra(vehicle, extraId, disable == 1)
end
end
end
if props.plate then SetVehicleNumberPlateText(vehicle, props.plate) end
if props.plateIndex then SetVehicleNumberPlateTextIndex(vehicle, props.plateIndex) end
if props.bodyHealth then SetVehicleBodyHealth(vehicle, props.bodyHealth + 0.0) end
if props.engineHealth then SetVehicleEngineHealth(vehicle, props.engineHealth + 0.0) end
if props.tankHealth then SetVehiclePetrolTankHealth(vehicle, props.tankHealth + 0.0) end
if props.fuelLevel then SetVehicleFuelLevel(vehicle, props.fuelLevel + 0.0) end
if props.oilLevel then SetVehicleOilLevel(vehicle, props.oilLevel + 0.0) end
if props.dirtLevel then SetVehicleDirtLevel(vehicle, props.dirtLevel + 0.0) end
-- Apply vehicle colors
if props.color1 then
if type(props.color1) == 'number' then
ClearVehicleCustomPrimaryColour(vehicle)
SetVehicleColours(vehicle, props.color1 --[[@as number]], colorSecondary --[[@as number]])
else
if props.paintType1 then
SetVehicleModColor_1(vehicle, props.paintType1, 0, props.pearlescentColor or 0)
end
SetVehicleCustomPrimaryColour(vehicle, props.color1[1], props.color1[2], props.color1[3])
end
end
if props.color2 then
if type(props.color2) == 'number' then
ClearVehicleCustomSecondaryColour(vehicle)
SetVehicleColours(vehicle, props.color1 or colorPrimary --[[@as number]], props.color2 --[[@as number]])
else
if props.paintType2 then
SetVehicleModColor_2(vehicle, props.paintType2, 0)
end
SetVehicleCustomSecondaryColour(vehicle, props.color2[1], props.color2[2], props.color2[3])
end
end
if props.pearlescentColor or props.wheelColor then
SetVehicleExtraColours(vehicle, props.pearlescentColor or pearlescentColor, props.wheelColor or wheelColor)
end
if props.interiorColor then SetVehicleInteriorColor(vehicle, props.interiorColor) end
if props.dashboardColor then SetVehicleDashboardColor(vehicle, props.dashboardColor) end
-- Apply wheel properties
if props.wheels then SetVehicleWheelType(vehicle, props.wheels) end
if props.wheelSize then SetVehicleWheelSize(vehicle, props.wheelSize) end
if props.wheelWidth then
SetVehicleWheelWidth(vehicle, props.wheelWidth)
end
-- Apply window and lighting properties
if props.windowTint then SetVehicleWindowTint(vehicle, props.windowTint) end
if props.neonEnabled then
for i = 1, #props.neonEnabled do
SetVehicleNeonLightEnabled(vehicle, i - 1, props.neonEnabled[i])
end
end
if props.neonColor then SetVehicleNeonLightsColour(vehicle, props.neonColor[1], props.neonColor[2], props.neonColor[3]) end
-- Apply vehicle damage
if props.windows then
for i = 1, #props.windows do
RemoveVehicleWindow(vehicle, props.windows[i])
end
end
if props.doors then
for i = 1, #props.doors do
SetVehicleDoorBroken(vehicle, props.doors[i], true)
end
end
if props.tyres then
for tyre, state in pairs(props.tyres) do
SetVehicleTyreBurst(vehicle, tonumber(tyre) --[[@as number]], state == 2, 1000.0)
end
end
if props.brokenWheels then
if type(props.brokenWheels) == 'number' then
BreakOffVehicleWheel(vehicle, props.brokenWheels --[[@as number]], false, true, true, false)
else
for i = 1, #props.brokenWheels do
BreakOffVehicleWheel(vehicle, props.brokenWheels[i], false, true, true, false)
end
end
end
if props.modSmokeEnabled ~= nil then ToggleVehicleMod(vehicle, 20, props.modSmokeEnabled) end
if props.tyreSmokeColor then SetVehicleTyreSmokeColor(vehicle, props.tyreSmokeColor[1], props.tyreSmokeColor[2], props.tyreSmokeColor[3]) end
if props.modSpoilers then SetVehicleMod(vehicle, 0, props.modSpoilers, false) end
if props.modFrontBumper then SetVehicleMod(vehicle, 1, props.modFrontBumper, false) end
if props.modRearBumper then SetVehicleMod(vehicle, 2, props.modRearBumper, false) end
if props.modSideSkirt then SetVehicleMod(vehicle, 3, props.modSideSkirt, false) end
if props.modExhaust then SetVehicleMod(vehicle, 4, props.modExhaust, false) end
if props.modFrame then SetVehicleMod(vehicle, 5, props.modFrame, false) end
if props.modGrille then SetVehicleMod(vehicle, 6, props.modGrille, false) end
if props.modHood then SetVehicleMod(vehicle, 7, props.modHood, false) end
if props.modFender then SetVehicleMod(vehicle, 8, props.modFender, false) end
if props.modRightFender then SetVehicleMod(vehicle, 9, props.modRightFender, false) end
if props.modRoof then SetVehicleMod(vehicle, 10, props.modRoof, false) end
if props.modEngine then SetVehicleMod(vehicle, 11, props.modEngine, false) end
if props.modBrakes then SetVehicleMod(vehicle, 12, props.modBrakes, false) end
if props.modTransmission then SetVehicleMod(vehicle, 13, props.modTransmission, false) end
if props.modSuspension then SetVehicleMod(vehicle, 15, props.modSuspension, false) end
if props.modArmor then SetVehicleMod(vehicle, 16, props.modArmor, false) end
if props.modNitrous then SetVehicleMod(vehicle, 17, props.modNitrous, false) end
if props.modTurbo ~= nil then ToggleVehicleMod(vehicle, 18, props.modTurbo) end
if props.modSubwoofer ~= nil then ToggleVehicleMod(vehicle, 19, props.modSubwoofer) end
if props.modHydraulics ~= nil then ToggleVehicleMod(vehicle, 21, props.modHydraulics) end
if props.modXenon ~= nil then ToggleVehicleMod(vehicle, 22, props.modXenon) end
if props.modHorns then SetVehicleMod(vehicle, 14, props.modHorns, false) end
if props.xenonColor then SetVehicleXenonLightsColor(vehicle, props.xenonColor) end
if props.modFrontWheels then SetVehicleMod(vehicle, 23, props.modFrontWheels, props.modCustomTiresF) end
if props.modBackWheels then SetVehicleMod(vehicle, 24, props.modBackWheels, props.modCustomTiresR) end
if props.modPlateHolder then SetVehicleMod(vehicle, 25, props.modPlateHolder, false) end
if props.modVanityPlate then SetVehicleMod(vehicle, 26, props.modVanityPlate, false) end
if props.modTrimA then SetVehicleMod(vehicle, 27, props.modTrimA, false) end
if props.modOrnaments then SetVehicleMod(vehicle, 28, props.modOrnaments, false) end
if props.modDashboard then SetVehicleMod(vehicle, 29, props.modDashboard, false) end
if props.modDial then SetVehicleMod(vehicle, 30, props.modDial, false) end
if props.modDoorSpeaker then SetVehicleMod(vehicle, 31, props.modDoorSpeaker, false) end
if props.modSeats then SetVehicleMod(vehicle, 32, props.modSeats, false) end
if props.modSteeringWheel then SetVehicleMod(vehicle, 33, props.modSteeringWheel, false) end
if props.modShifterLeavers then SetVehicleMod(vehicle, 34, props.modShifterLeavers, false) end
if props.modAPlate then SetVehicleMod(vehicle, 35, props.modAPlate, false) end
if props.modSpeakers then SetVehicleMod(vehicle, 36, props.modSpeakers, false) end
if props.modTrunk then SetVehicleMod(vehicle, 37, props.modTrunk, false) end
if props.modHydrolic then SetVehicleMod(vehicle, 38, props.modHydrolic, false) end
if props.modEngineBlock then SetVehicleMod(vehicle, 39, props.modEngineBlock, false) end
if props.modAirFilter then SetVehicleMod(vehicle, 40, props.modAirFilter, false) end
if props.modStruts then SetVehicleMod(vehicle, 41, props.modStruts, false) end
if props.modArchCover then SetVehicleMod(vehicle, 42, props.modArchCover, false) end
if props.modAerials then SetVehicleMod(vehicle, 43, props.modAerials, false) end
if props.modTrimB then SetVehicleMod(vehicle, 44, props.modTrimB, false) end
if props.modTank then SetVehicleMod(vehicle, 45, props.modTank, false) end
if props.modWindows then SetVehicleMod(vehicle, 46, props.modWindows, false) end
if props.modDoorR then SetVehicleMod(vehicle, 47, props.modDoorR, false) end
if props.modLivery then SetVehicleMod(vehicle, 48, props.modLivery, false) end
if props.modLightbar then SetVehicleMod(vehicle, 49, props.modLightbar, false) end
if props.modRoofLivery then SetVehicleRoofLivery(vehicle, props.modRoofLivery) end
if props.livery then SetVehicleLivery(vehicle, props.livery) end
if props.bulletProofTyres ~= nil then SetVehicleTyresCanBurst(vehicle, props.bulletProofTyres) end
if gameBuild >= 2372 and props.driftTyres then SetDriftTyresEnabled(vehicle, true) end
if props.doorLockStatus then
SetVehicleDoorsLocked(vehicle, props.doorLockStatus)
end
if not DecorExistOn(vehicle, "Player_Vehicle") then DecorSetInt(vehicle, "Player_Vehicle", -1) end
-- Only sync to other clients if not called from state bag AND we own the entity
if not fromStateBag and NetworkGetEntityIsNetworked(vehicle) and NetworkGetEntityOwner(vehicle) == PlayerId() then
Entity(vehicle).state:set('community_bridge:SetVehicleProperties', props, true)
if props.doorLockStatus then Entity(vehicle).state:set('door', tonumber(props.doorLockStatus), true) end
end
return true
end
return Vehicles
+6
View File
@@ -7,6 +7,12 @@ Banking.GetManagmentName = function()
return 'default'
end
---This will get the name of the in use resource.
---@return string
Banking.GetResourceName = function()
return 'default'
end
---This will return a number
---@param account string
---@return number
+6
View File
@@ -10,6 +10,12 @@ Banking.GetManagmentName = function()
return 'fd_banking'
end
---This will get the name of the in use resource.
---@return string
Banking.GetResourceName = function()
return 'fd_banking'
end
---This will return a number
---@param account string
---@return number
@@ -10,6 +10,12 @@ Banking.GetManagmentName = function()
return 'kartik-banking'
end
---This will get the name of the in use resource.
---@return string
Banking.GetResourceName = function()
return 'kartik-banking'
end
---This will return a number
---@param account string
---@return number
+6
View File
@@ -10,6 +10,12 @@ Banking.GetManagmentName = function()
return 'okokBanking'
end
---This will get the name of the in use resource.
---@return string
Banking.GetResourceName = function()
return 'okokBanking'
end
---This will return a number
---@param account string
---@return number
+6
View File
@@ -10,6 +10,12 @@ Banking.GetManagmentName = function()
return 'qb-banking'
end
---This will get the name of the in use resource.
---@return string
Banking.GetResourceName = function()
return 'qb-banking'
end
---This will return a number
---@param account string
---@return number
@@ -10,6 +10,12 @@ Banking.GetManagmentName = function()
return 'Renewed-Banking'
end
---This will get the name of the in use resource.
---@return string
Banking.GetResourceName = function()
return 'Renewed-Banking'
end
---This will return a number
---@param account string
---@return number
+6
View File
@@ -10,6 +10,12 @@ Banking.GetManagmentName = function()
return 'tgg-banking'
end
---This will get the name of the in use resource.
---@return string
Banking.GetResourceName = function()
return 'tgg-banking'
end
---This will return a number
---@param account string
---@return number
+6
View File
@@ -10,6 +10,12 @@ Banking.GetManagmentName = function()
return 'tgiann-bank'
end
---This will get the name of the in use resource.
---@return string
Banking.GetResourceName = function()
return 'tgiann-bank'
end
---This will return a number
---@param account string
---@return number
@@ -10,6 +10,12 @@ Banking.GetManagmentName = function()
return 'wasabi_banking'
end
---This will get the name of the in use resource.
---@return string
Banking.GetResourceName = function()
return 'wasabi_banking'
end
---This will return a number
---@param account string
---@return number
+8 -1
View File
@@ -2,7 +2,7 @@
Clothing = Clothing or {}
ClothingBackup = {}
Callback = Callback or Require("lib/utility/shared/callbacks.lua")
Callback = Callback or Require("lib/callback/shared/callback.lua")
Ultility = Utility or Require('lib/utility/client/utility.lua')
Cache = Cache or Require('lib/cache/shared/cache.lua')
@@ -16,6 +16,13 @@ function Clothing.IsMale()
return false
end
---This will get the name of the in use resource.
---@return string
Clothing.GetResourceName = function()
return 'default'
end
---Get the skin data of a ped
---@param entity number
---@return table
+7 -1
View File
@@ -1,7 +1,7 @@
---@diagnostic disable: duplicate-set-field
Clothing = Clothing or {}
Clothing.LastAppearance = Clothing.LastAppearance or {}
Callback = Callback or Require("lib/utility/shared/callbacks.lua")
Callback = Callback or Require("lib/callback/shared/callback.lua")
function Clothing.IsMale(src)
local ped = GetPlayerPed(src)
@@ -9,6 +9,12 @@ function Clothing.IsMale(src)
return GetEntityModel(ped) == `mp_m_freemode_01`
end
---This will get the name of the in use resource.
---@return string
Clothing.GetResourceName = function()
return 'default'
end
function Clothing.GetAppearance(src)
return Callback.Trigger('community_bridge:cb:GetAppearance', src)
end
+6
View File
@@ -6,3 +6,9 @@ Clothing = Clothing or {}
function Clothing.OpenMenu()
TriggerEvent('esx_skin:openMenu', function() end, function() end, true)
end
---This will get the name of the in use resource.
---@return string
Clothing.GetResourceName = function()
return 'esx_skin'
end
+6
View File
@@ -35,6 +35,12 @@ function Clothing.GetFullAppearanceData(src)
return Clothing.Players[citId]
end
---This will get the name of the in use resource.
---@return string
Clothing.GetResourceName = function()
return 'esx_skin'
end
---Retrieves a player's converted appearance data for easy use across modules
---@param src number The server ID of the player
---@param fullData boolean Optional - If true, returns the full data object including skin and model
@@ -6,3 +6,9 @@ Clothing = Clothing or {}
function Clothing.OpenMenu()
TriggerEvent('qb-clothing:client:openMenu')
end
---This will get the name of the in use resource.
---@return string
Clothing.GetResourceName = function()
return 'fivem-appearance'
end
@@ -44,6 +44,12 @@ function Clothing.GetFullAppearanceData(src)
return Clothing.Players[citId]
end
---This will get the name of the in use resource.
---@return string
Clothing.GetResourceName = function()
return 'fivem-appearance'
end
--- Retrieves a player's converted appearance data for easy use across modules
---@param src number The server ID of the player
---@param fullData boolean Optional - If true, returns the full data object including skin and model
@@ -6,3 +6,9 @@ Clothing = Clothing or {}
function Clothing.OpenMenu()
TriggerEvent('qb-clothing:client:openMenu')
end
---This will get the name of the in use resource.
---@return string
Clothing.GetResourceName = function()
return 'illenium-appearance'
end
@@ -35,6 +35,12 @@ function Clothing.GetFullAppearanceData(src)
return Clothing.Players[citId]
end
---This will get the name of the in use resource.
---@return string
Clothing.GetResourceName = function()
return 'illenium-appearance'
end
--- Retrieves a player's converted appearance data for easy use across modules
---@param src number The server ID of the player
---@param fullData boolean Optional - If true, returns the full data object including skin and model
+6
View File
@@ -6,3 +6,9 @@ Clothing = Clothing or {}
function Clothing.OpenMenu()
TriggerEvent('qb-clothing:client:openMenu')
end
---This will get the name of the in use resource.
---@return string
Clothing.GetResourceName = function()
return 'qb-clothing'
end
+6
View File
@@ -38,6 +38,12 @@ function Clothing.GetFullAppearanceData(src)
return Clothing.Players[citId]
end
---This will get the name of the in use resource.
---@return string
Clothing.GetResourceName = function()
return 'qb-clothing'
end
--- Retrieves a player's converted appearance data for easy use across modules
---@param src number The server ID of the player
---@param fullData boolean Optional - If true, returns the full data object including skin and model
@@ -4,4 +4,10 @@ Clothing = Clothing or {}
function Clothing.OpenMenu()
TriggerEvent('qb-clothing:client:openMenu')
end
---This will get the name of the in use resource.
---@return string
Clothing.GetResourceName = function()
return 'rcore_clothing'
end
@@ -94,64 +94,4 @@ RegisterNuiCallback("dialogue:SelectOption", function(data)
promis(data.id)
end)
-- Debug command
if BridgeSharedConfig.DebugLevel >= 1 then
-- RegisterCommand("dialogue", function()
-- local pos = GetOffsetFromEntityInWorldCoords(PlayerPedId(), 0, 2.0, 0)
-- local timeout = 500
-- local model = `a_f_y_hipster_01`
-- RequestModel(model)
-- while not HasModelLoaded(model) do
-- Wait(0)
-- timeout = timeout - 1
-- if timeout == 0 then
-- print("Failed to load model")
-- return
-- end
-- end
-- local ped = CreatePed(0, model, pos.x, pos.y, pos.z, 0.0, false, false)
-- local characterData = {
-- entity = ped,
-- offset = vector3(0, 0, 0),
-- rotationOffset = vector3(0, 0, 0)
-- }
-- Wait(750)
-- Dialogue.Open("Akmed", "Hello how are you doing my friend?", characterData, {
-- {
-- label = "Trade with me",
-- id = 'something',
-- },
-- {
-- label = "Goodbye",
-- id = 'someotherthing',
-- },
-- },
-- function(selectedId)
-- if selectedId == 'something' then
-- Dialogue.Open( "Akmed" , "Thank you for wanting to purchase me lucky charms", characterData, {
-- {
-- label = "Fuck off",
-- id = 'something',
-- },
-- {
-- label = "Goodbye",
-- id = 'someotherthing',
-- },
-- },
-- function(selectedId)
-- DeleteEntity(ped)
-- if selectedId == "something" then
-- print("You hate lucky charms")
-- else
-- print("Thanks for keeping it civil")
-- end
-- end)
-- else
-- DeleteEntity(ped)
-- end
-- end)
-- end)
end
return Dialogue
@@ -30,4 +30,10 @@ RegisterNetEvent('community_bridge:Client:DispatchAlert', function(alert)
Bridge.Utility.RemoveBlip(blip)
end)
---This will get the name of the in use resource.
---@return string
Dispatch.GetResourceName = function()
return 'default'
end
return Dispatch
@@ -10,4 +10,10 @@ RegisterNetEvent("community_bridge:Server:DispatchAlert", function(data)
end
end)
---This will get the name of the in use resource.
---@return string
Dispatch.GetResourceName = function()
return 'default'
end
return Dispatch
@@ -16,4 +16,10 @@ Dispatch.SendAlert = function(data)
exports["bub-mdt"]:CustomAlert(alertData)
end
---This will get the name of the in use resource.
---@return string
Dispatch.GetResourceName = function()
return 'bub-mdt'
end
return Dispatch
@@ -1,4 +1,10 @@
if GetResourceState('bub-mdt') == 'missing' then return end
Dispatch = Dispatch or {}
---This will get the name of the in use resource.
---@return string
Dispatch.GetResourceName = function()
return 'bub-mdt'
end
return Dispatch
@@ -24,4 +24,10 @@ Dispatch.SendAlert = function(data)
})
end
---This will get the name of the in use resource.
---@return string
Dispatch.GetResourceName = function()
return 'cd_dispatch'
end
return Dispatch
@@ -1,4 +1,10 @@
if GetResourceState('cd_dispatch') == 'missing' then return end
Dispatch = Dispatch or {}
---This will get the name of the in use resource.
---@return string
Dispatch.GetResourceName = function()
return 'cd_dispatch'
end
return Dispatch
@@ -27,4 +27,10 @@ Dispatch.SendAlert = function(data)
exports['kartik-mdt']:CustomAlert(alertOptions)
end
---This will get the name of the in use resource.
---@return string
Dispatch.GetResourceName = function()
return 'kartik-mdt'
end
return Dispatch
@@ -1,4 +1,10 @@
if GetResourceState('kartik-mdt') == 'missing' then return end
Dispatch = Dispatch or {}
---This will get the name of the in use resource.
---@return string
Dispatch.GetResourceName = function()
return 'kartik-mdt'
end
return Dispatch
@@ -40,4 +40,10 @@ Dispatch.SendAlert = function(data)
TriggerServerEvent("community_bridge:server:dispatch:sendAlert", alertData)
end
---This will get the name of the in use resource.
---@return string
Dispatch.GetResourceName = function()
return 'lb-tablet'
end
return Dispatch
@@ -5,4 +5,10 @@ RegisterNetEvent("community_bridge:server:dispatch:sendAlert", function(data)
exports["lb-tablet"]:AddDispatch(data) -- this has a return value but we dont really have a use for it atm.
end)
---This will get the name of the in use resource.
---@return string
Dispatch.GetResourceName = function()
return 'lb-tablet'
end
return Dispatch
@@ -19,4 +19,10 @@ Dispatch.SendAlert = function(data)
})
end
---This will get the name of the in use resource.
---@return string
Dispatch.GetResourceName = function()
return 'linden_outlawalert'
end
return Dispatch
@@ -1,4 +1,10 @@
if GetResourceState('linden_outlawalert') == 'missing' then return end
Dispatch = Dispatch or {}
---This will get the name of the in use resource.
---@return string
Dispatch.GetResourceName = function()
return 'linden_outlawalert'
end
return Dispatch
@@ -1,4 +1,10 @@
if GetResourceState('origen_police') == 'missing' then return end
Dispatch = Dispatch or {}
---This will get the name of the in use resource.
---@return string
Dispatch.GetResourceName = function()
return 'origen_police'
end
return Dispatch
@@ -7,4 +7,10 @@ Dispatch.SendAlert = function(data)
TriggerServerEvent('community_bridge:Server:piotreq_gpt', data)
end
---This will get the name of the in use resource.
---@return string
Dispatch.GetResourceName = function()
return 'piotreq_gpt'
end
return Dispatch
@@ -36,4 +36,10 @@ RegisterNetEvent('community_bridge:Server:piotreq_gpt', function(data)
Dispatch.SendAlert(src, data)
end)
---This will get the name of the in use resource.
---@return string
Dispatch.GetResourceName = function()
return 'piotreq_gpt'
end
return Dispatch
@@ -27,4 +27,10 @@ Dispatch.SendAlert = function(data)
exports["ps-dispatch"]:CustomAlert(alertData)
end
---This will get the name of the in use resource.
---@return string
Dispatch.GetResourceName = function()
return 'ps-dispatch'
end
return Dispatch
@@ -2,4 +2,10 @@ if GetResourceState('ps-dispatch') == 'missing' then return end
if GetResourceState('lb-tablet') == 'started' then return end
Dispatch = Dispatch or {}
---This will get the name of the in use resource.
---@return string
Dispatch.GetResourceName = function()
return 'ps-dispatch'
end
return Dispatch
@@ -38,4 +38,11 @@ Dispatch.SendAlert = function(data)
end)
end
---This will get the name of the in use resource.
---@return string
Dispatch.GetResourceName = function()
return 'qs-dispatch'
end
return Dispatch
@@ -1,4 +1,11 @@
if GetResourceState('qs-dispatch') == 'missing' then return end
Dispatch = Dispatch or {}
---This will get the name of the in use resource.
---@return string
Dispatch.GetResourceName = function()
return 'qs-dispatch'
end
return Dispatch
@@ -14,4 +14,11 @@ Dispatch.SendAlert = function(data)
TriggerServerEvent("community_bridge:server:dispatch:sendAlert", alertData)
end
---This will get the name of the in use resource.
---@return string
Dispatch.GetResourceName = function()
return 'redutzu-mdt'
end
return Dispatch
@@ -11,4 +11,10 @@ RegisterNetEvent("community_bridge:server:dispatch:sendAlert", function(data)
})
end)
---This will get the name of the in use resource.
---@return string
Dispatch.GetResourceName = function()
return 'redutzu-mdt'
end
return Dispatch
@@ -20,4 +20,10 @@ Dispatch.SendAlert = function(data)
})
end
---This will get the name of the in use resource.
---@return string
Dispatch.GetResourceName = function()
return 'tk_dispatch'
end
return Dispatch
@@ -1,4 +1,10 @@
if GetResourceState('tk_dispatch') == 'missing' then return end
Dispatch = Dispatch or {}
---This will get the name of the in use resource.
---@return string
Dispatch.GetResourceName = function()
return 'tk_dispatch'
end
return Dispatch
+6
View File
@@ -10,4 +10,10 @@ Doorlock.ToggleDoorLock = function(doorID, toggle)
return true
end
---This will get the name of the in use resource.
---@return string
Doorlock.GetResourceName = function()
return 'default'
end
return Doorlock
@@ -9,4 +9,10 @@ Doorlock.GetClosestDoor = function()
return exports["doors_creator"]:getClosestActiveDoor()
end
---This will get the name of the in use resource.
---@return string
Doorlock.GetResourceName = function()
return 'doors_creator'
end
return Doorlock
@@ -18,4 +18,10 @@ Doorlock.ToggleDoorLock = function(doorID, toggle)
return true
end
---This will get the name of the in use resource.
---@return string
Doorlock.GetResourceName = function()
return 'doors_creator'
end
return Doorlock
+6
View File
@@ -11,4 +11,10 @@ Doorlock.GetClosestDoor = function()
return tostring(doorData.id) or nil
end
---This will get the name of the in use resource.
---@return string
Doorlock.GetResourceName = function()
return 'ox_doorlock'
end
return Doorlock
+10 -1
View File
@@ -4,10 +4,13 @@ if GetResourceState('ox_doorlock') == 'missing' then return end
Doorlock = Doorlock or {}
---This will toggle the lock status of the door.
---@param doorID string
---@param doorID string|number
---@param toggle boolean
---@return boolean
Doorlock.ToggleDoorLock = function(doorID, toggle)
if type(doorID) == 'string' then
doorID = tonumber(doorID)
end
local state = toggle
if state then
exports.ox_doorlock:setDoorState(doorID, 1)
@@ -17,4 +20,10 @@ Doorlock.ToggleDoorLock = function(doorID, toggle)
return true
end
---This will get the name of the in use resource.
---@return string
Doorlock.GetResourceName = function()
return 'ox_doorlock'
end
return Doorlock
+6
View File
@@ -23,4 +23,10 @@ Doorlock.GetClosestDoor = function()
return door
end
---This will get the name of the in use resource.
---@return string
Doorlock.GetResourceName = function()
return 'qb-doorlock'
end
return Doorlock
+6
View File
@@ -12,4 +12,10 @@ Doorlock.ToggleDoorLock = function(doorID, toggle)
return true
end
---This will get the name of the in use resource.
---@return string
Doorlock.GetResourceName = function()
return 'qb-doorlock'
end
return Doorlock
@@ -21,4 +21,10 @@ Doorlock.GetClosestDoor = function()
return door
end
---This will get the name of the in use resource.
---@return string
Doorlock.GetResourceName = function()
return 'rcore_doorlock'
end
return Doorlock
@@ -16,4 +16,11 @@ Doorlock.ToggleDoorLock = function(doorID, toggle)
end
return true
end
---This will get the name of the in use resource.
---@return string
Doorlock.GetResourceName = function()
return 'rcore_doorlock'
end
return Doorlock
+33
View File
@@ -1,3 +1,36 @@
---@diagnostic disable: duplicate-set-field
Framework = Framework or {}
local currentJobCounts = GlobalState.jobcounts or {}
AddStateBagChangeHandler('jobcounts', 'global', function(bagName, key, value)
if not value then currentJobCounts = {} return end
currentJobCounts = value
end)
---This will get the name of the in use resource.
---@return string
Framework.GetResourceName = function()
return 'default'
end
---This is an internal function that will be used to retrieve job counts later.
---@param jobName string
---@return number
Framework.GetJobCount = function(jobName)
if not currentJobCounts[jobName] then return 0 end
return currentJobCounts[jobName]
end
---This will allow passing a table of job names and returning a sum of the total count.
---@param tbl table
---@return number
Framework.GetJobCountTotal = function(tbl)
local total = 0
for _, jobName in pairs(tbl) do
total = total + Framework.GetJobCount(jobName)
end
return total
end
return Framework
+70 -12
View File
@@ -1,13 +1,39 @@
---@diagnostic disable: duplicate-set-field
Framework = Framework or {}
local jobsRegisteredTable = {}
local invertedJobsRegisteredTable = {}
local globalState = GlobalState
globalState.jobcounts = {}
---This will get the name of the in use resource.
---@return string
Framework.GetResourceName = function()
return 'default'
end
---This is an internal function that will be used to retrieve job counts later.
---@param jobName string
---@return number
Framework.GetJobCount = function(jobName)
return #jobsRegisteredTable[jobName] or 0
if not jobsRegisteredTable[jobName] then return 0 end
local count = 0
for _ in pairs(jobsRegisteredTable[jobName]) do
count = count + 1
end
return count
end
---This will allow passing a table of job names and returning a sum of the total count.
---@param tbl any
---@return number
Framework.GetJobCountTotal = function(tbl)
local total = 0
for _, jobName in pairs(tbl) do
total = total + Framework.GetJobCount(jobName)
end
return total
end
---This will return a list of player sources for a given job.
@@ -15,7 +41,11 @@ end
---@return table
Framework.GetPlayerSourcesByJob = function(jobName)
if not jobsRegisteredTable[jobName] then return {} end
return jobsRegisteredTable[jobName]
local sources = {}
for src in pairs(jobsRegisteredTable[jobName]) do
table.insert(sources, src)
end
return sources
end
---This will update the cached tables for job counts.
@@ -23,18 +53,25 @@ end
---@param src number
---@param jobName string
Framework.AddJobCount = function(src, jobName)
if not src or not jobName then return false end
if not jobsRegisteredTable[jobName] then jobsRegisteredTable[jobName] = {} end
if jobsRegisteredTable[jobName][src] then return false end
jobsRegisteredTable[jobName][src] = true
invertedJobsRegisteredTable[src] = jobName
return true, #jobsRegisteredTable[jobName]
local newJobCounts = {}
for job, _ in pairs(jobsRegisteredTable) do
newJobCounts[job] = Framework.GetJobCount(job)
end
globalState.jobcounts = newJobCounts
return true
end
---This will return the job name for a given source.
---This is an internal function that will be used to retrieve job names in situations where player data is unavailable.
---@param src number
Framework.SearchJobCountBySource = function(src)
if not invertedJobsRegisteredTable[src] then return nil end
return invertedJobsRegisteredTable[src]
end
@@ -42,15 +79,36 @@ end
---@param src number
---@param jobName string | nil
Framework.RemoveJobCount = function(src, jobName)
if not jobName then
jobName = Framework.SearchJobCountBySource(src)
end
if not src then return false end
if not jobName then jobName = invertedJobsRegisteredTable[src] end
if not jobName then return false end
if not jobsRegisteredTable[jobName] then return false end
if not jobsRegisteredTable[jobName][src] then return false end
invertedJobsRegisteredTable[src] = nil
jobsRegisteredTable[jobName][src] = nil
return true, #jobsRegisteredTable[jobName]
if jobsRegisteredTable[jobName] then
jobsRegisteredTable[jobName][src] = nil
end
local newJobCounts = {}
for job, _ in pairs(jobsRegisteredTable) do
local count = Framework.GetJobCount(job)
if count > 0 then
newJobCounts[job] = count
end
end
globalState.jobcounts = newJobCounts
return true
end
AddEventHandler('community_bridge:Server:OnPlayerJobChange', function(src, newJobName)
local previousJob = invertedJobsRegisteredTable[src]
if previousJob then Framework.RemoveJobCount(src, previousJob) end
if newJobName then Framework.AddJobCount(src, newJobName) end
end)
AddEventHandler('community_bridge:Server:OnPlayerUnload', function(src)
Framework.RemoveJobCount(src)
end)
return Framework
+97 -62
View File
@@ -1,13 +1,14 @@
---@diagnostic disable: duplicate-set-field
if GetResourceState('es_extended') ~= 'started' then return end
ESX = exports["es_extended"]:getSharedObject()
Callback = Callback or Require("lib/utility/shared/callbacks.lua")
ESX = exports.es_extended:getSharedObject()
Callback = Callback or Require("lib/callback/shared/callback.lua")
Framework = Framework or {}
local cachedItemList = nil
-- This is an internal function, its here to attempt to emulate qbs shared items mainly.
--- @description This is an internal function, its here to attempt to emulate qbs shared items mainly
Framework.ItemList = function()
if cachedItemList then return cachedItemList end
local items = Callback.Trigger('community_bridge:Callback:GetFrameworkItems', false)
@@ -15,98 +16,105 @@ Framework.ItemList = function()
return cachedItemList
end
---This will get the name of the framework being used (if a supported framework).
---@return string
--- @description This will get the name of the framework being used (if a supported framework).
--- @return string
Framework.GetFrameworkName = function()
return 'es_extended'
end
---This will return true if the player is loaded, false otherwise.
---This could be useful in scripts that rely on player loaded events and offer a debug mode to hit this function.
---@return boolean
---This will get the name of the in use resource.
---@return string
Framework.GetResourceName = function()
return 'es_extended'
end
--- @description This will return true if the player is loaded, false otherwise.
--- This could be useful in scripts that rely on player loaded events and offer a debug mode to hit this function
--- @return boolean
Framework.GetIsPlayerLoaded = function()
return ESX.IsPlayerLoaded()
end
---This will return a table of the player data, this will be in the framework format.
---This is mainly for internal bridge use and should be avoided.
---@return table
--- @description This will return a table of the player data, this will be in the framework format
--- This is mainly for internal bridge use and should be avoided.
--- @return table
Framework.GetPlayerData = function()
return ESX.GetPlayerData()
end
---This will return a table of all the jobs in the framework.
---@return table
--- @description This will return a table of all the jobs in the framework.
--- @return table
Framework.GetFrameworkJobs = function()
local jobs = Callback.Trigger('community_bridge:Callback:GetFrameworkJobs', false)
return jobs
end
---This will return the players birth date
---@return string
--- @description This will return the players birth date
--- @return string
Framework.GetPlayerDob = function()
local playerData = Framework.GetPlayerData()
local dob = playerData.dateofbirth
return dob
end
---This will return the players metadata for the specified metadata key.
---@param metadata table | string
--- @description This will return the players metadata for the specified metadata key.
--- @param metadata table | string
---@return table | string | number | boolean
Framework.GetPlayerMetaData = function(metadata)
return Framework.GetPlayerData().metadata[metadata]
end
---This will send a notification to the player.
---@param message string
---@param type string
---@param time number
---@return nil
--- @description This will send a notification to the player.
--- @param message string
--- @param type string
--- @param time number
--- @return nil
Framework.Notify = function(message, type, time)
return ESX.ShowNotification(message, type, time)
end
---Will Display the help text message on the screen
---@param message string
---@param _ unknown
---@return nil
--- @description This will display the help text message on the screen
--- @param message string
--- @param _ unknown
--- @return nil
Framework.ShowHelpText = function(message, _)
return exports['esx_textui']:TextUI(message, "info")
return exports.esx_textui:TextUI(message, "info")
end
---This will hide the help text message on the screen
---@return nil
--- @description This will hide the help text message on the screen
--- @return nil
Framework.HideHelpText = function()
return exports['esx_textui']:HideUI()
return exports.esx_textui:HideUI()
end
---This will get the players identifier (citizenid) etc.
--- @description This will get the players identifier (citizenid) etc.
---@return string
Framework.GetPlayerIdentifier = function()
local playerData = Framework.GetPlayerData()
return playerData.identifier
end
---This will get the players name (first and last).
---@return string
---@return string
--- @description This will get the players name (first and last).
--- @return string
--- @return string
Framework.GetPlayerName = function()
local playerData = Framework.GetPlayerData()
return playerData.firstName, playerData.lastName
end
---Depricated : This will return the players job name, job label, job grade label and job grade level
---@return string
---@return string
---@return string
---@return string
--- @deprecated This will return the players job name, job label, job grade label and job grade level
--- @return string returns job name
--- @return string returns job label
--- @return string returns job grade label
--- @return string returns job grade level
Framework.GetPlayerJob = function()
local playerData = Framework.GetPlayerData()
return playerData.job.name, playerData.job.label, playerData.job.grade_label, playerData.job.grade
end
---This will return the players job name, job label, job grade label job grade level, boss status, and duty status in a table
---@return table
--- @description This will return the players job name, job label, job grade label job grade level,
--- boss status, and duty status in a table
--- @return table
Framework.GetPlayerJobData = function()
local playerData = Framework.GetPlayerData()
local jobData = playerData.job
@@ -122,34 +130,61 @@ Framework.GetPlayerJobData = function()
}
end
---This will return if the player has the specified item in their inventory.
---@param item string
---@return boolean
--This is an internal function to get status data
--- @param search string
Framework.GetStatusData = function(search)
local playerData = Framework.GetPlayerData()
if not playerData then return 0 end
local status = playerData.variables.status
for _, entry in ipairs(status) do
if entry.name == search then
return entry.percent or 0
end
end
return 0
end
---This will get the hunger of a player
---@return number
Framework.GetHunger = function()
local status = Framework.GetStatusData("hunger")
return math.floor((status) + 0.5) or 0
end
---This will get the thirst of a player
---@return number
Framework.GetThirst = function()
local status = Framework.GetStatusData("thirst")
return math.floor((status) + 0.5) or 0
end
--- @description This will return if the player has the specified item in their inventory
--- @param item string
--- @return boolean
Framework.HasItem = function(item)
local hasItem = ESX.SearchInventory(item, true)
return hasItem > 0 and true or false
end
---This will return the item count for the specified item in the players inventory.
---@param item string
---@return number
--- @description This will return the item count for the specified item in the players inventory
--- @param item string
--- @return number
Framework.GetItemCount = function(item)
local inventory = Framework.GetPlayerInventory()
if not inventory then return 0 end
return inventory[item].count or 0
end
---This will return a table of the players inventory
---@return table
--- @description This will return a table of the players inventory
--- @return table
Framework.GetPlayerInventory = function()
local playerData = Framework.GetPlayerData()
return playerData.inventory
end
---This will return the players money by type, I recommend not useing this as its the client and not secure or to be trusted.
---Use case is for a ui or a menu I guess.
---@param _type string
---@return number
--- @description This will return the players money by type, I recommend not using this as its the client and not secure or to be trusted
--- @param _type string
--- @return number
Framework.GetAccountBalance = function(_type)
local player = Framework.GetPlayerData()
if not player then return 0 end
@@ -163,19 +198,19 @@ Framework.GetAccountBalance = function(_type)
return 0
end
---This will return the vehicle properties for the specified vehicle.
---@param vehicle number
---@return table
--- @description This will return the vehicle properties for the specified vehicle
--- @param vehicle number
--- @return table
Framework.GetVehicleProperties = function(vehicle)
if not vehicle or not DoesEntityExist(vehicle) then return {} end
local vehicleProps = ESX.Game.GetVehicleProperties(vehicle)
return vehicleProps or {}
end
---This will set the vehicle properties for the specified vehicle.
---@param vehicle number
---@param properties table
---@return boolean
--- @description This will set the vehicle properties for the specified vehicle
--- @param vehicle number
--- @param properties table
--- @return boolean
Framework.SetVehicleProperties = function(vehicle, properties)
if not vehicle or not DoesEntityExist(vehicle) then return false end
if not properties then return false end
@@ -203,8 +238,8 @@ Framework.SetVehicleProperties = function(vehicle, properties)
return true, ESX.Game.SetVehicleProperties(vehicle, properties)
end
---This will get a players dead status.
---@return boolean
--- @description This will get a players dead status
--- @return boolean
Framework.GetIsPlayerDead = function()
local playerData = Framework.GetPlayerData()
return playerData.dead
+158 -146
View File
@@ -2,21 +2,27 @@
if GetResourceState('es_extended') ~= 'started' then return end
Prints = Prints or Require("lib/utility/shared/prints.lua")
Callback = Callback or Require("lib/utility/shared/callbacks.lua")
Callback = Callback or Require("lib/callback/shared/callback.lua")
ESX = exports["es_extended"]:getSharedObject()
ESX = exports.es_extended:getSharedObject()
Framework = Framework or {}
local cachedItemList = nil
---This will return the name of the framework in use.
---@return string
--- @description This will return the name of the framework in use
--- @return string
Framework.GetFrameworkName = function()
return 'es_extended'
end
-- This is an internal function, its here to attempt to emulate qbs shared items mainly.
---This will get the name of the in use resource.
---@return string
Framework.GetResourceName = function()
return 'es_extended'
end
--- @description This is an internal function, its here to attempt to emulate qbs shared items mainly
Framework.ItemList = function()
if cachedItemList then return cachedItemList end
local items = ESX.Items
@@ -40,9 +46,9 @@ Framework.ItemList = function()
return cachedItemList
end
---This will return if the player is an admin in the framework.
---@param src any
---@return boolean
--- @description This will return if the player is an admin in the framework
--- @param src any
--- @return boolean
Framework.GetIsFrameworkAdmin = function(src)
if not src then return false end
local xPlayer = Framework.GetPlayer(src)
@@ -52,8 +58,8 @@ Framework.GetIsFrameworkAdmin = function(src)
return false
end
---This will get the players birth date
---@return string|nil
--- @description This will get the players birth date
--- @return string|nil
Framework.GetPlayerDob = function(src)
local xPlayer = Framework.GetPlayer(src)
if not xPlayer then return end
@@ -61,43 +67,40 @@ Framework.GetPlayerDob = function(src)
return dob
end
--- Returns the player data of the specified source in the framework defualt format.
---@param src any
---@return table | nil
--- @description Returns the player data of the specified source in the framework defualt format
--- @param src any
--- @return table | nil
Framework.GetPlayer = function(src)
local xPlayer = ESX.GetPlayerFromId(src)
if not xPlayer then return end
return xPlayer
end
-- Framework.GetPlayerIdentifier(src)
-- Returns the citizen ID of the player.
---@param src number
---@return string | nil
--- @description Returns the citizen ID of the player.
--- @param src number
--- @return string | nil returns the citizen ID of the player if it exists
Framework.GetPlayerIdentifier = function(src)
local xPlayer = Framework.GetPlayer(src)
if not xPlayer then return end
return xPlayer.getIdentifier()
end
---This will return the jobs registered in the framework in a table.
---Format of the table is:
---{name = jobName, label = jobLabel, grade = {name = gradeName, level = gradeLevel}}
---@return table
--- @description This will return the jobs registered in the framework in a table.
--- @return table in the format "{name = jobName, label = jobLabel, grade = {name = gradeName, level = gradeLevel}}"
Framework.GetFrameworkJobs = function()
return ESX.GetJobs()
end
-- Framework.GetPlayerName(src)
-- Returns the first and last name of the player.
---@return string|nil, string|nil
--- @description This will return the first and last name of the player.
--- @return string|nil, string|nil returns the first and last name of the player
Framework.GetPlayerName = function(src)
local xPlayer = Framework.GetPlayer(src)
if not xPlayer then return end
return xPlayer.variables.firstName, xPlayer.variables.lastName
end
---This will return a table of all logged in players
---@return table
--- @description This will return a table of all logged in players
--- @return table
Framework.GetPlayers = function()
local players = ESX.GetExtendedPlayers()
local playerList = {}
@@ -107,12 +110,11 @@ Framework.GetPlayers = function()
return playerList
end
---Returns a table of items matching the specified name and if passed metadata from the player's inventory.
---returns {name = v.name, count = v.amount, metadata = v.info, slot = v.slot}
---@param src number
---@param item string
---@param _ table
---@return table|nil
--- @description This will return a table of items matching the specified name and if passed metadata from the player's inventory
--- @param src number
--- @param item string
--- @param _ table
--- @return table|nil returns {name = v.name, count = v.amount, metadata = v.info, slot = v.slot}
Framework.GetItem = function(src, item, _)
local xPlayer = Framework.GetPlayer(src)
if not xPlayer then return end
@@ -131,32 +133,29 @@ Framework.GetItem = function(src, item, _)
return repackedTable
end
---This will return the count of the item in the players inventory, if not found will return 0.
---if metadata is passed it will find the matching items count (esx_core does not feature metadata items).
---@param src number
---@param item string
---@param _ table
---@return number
--- @param src number
--- @param item string
--- @param _ table
--- @return number returns the count of the item in the players inventory, if not found will return 0.
--- If metadata is passed it will find the matching items count (esx_core does not feature metadata items)
Framework.GetItemCount = function(src, item, _)
local xPlayer = Framework.GetPlayer(src)
if not xPlayer then return end
return xPlayer.getInventoryItem(item).count
end
---This will return a boolean if the player has the item.
---@param src number
---@param item string
---@return boolean
--- @description This will return true if the player has the item, false otherwise
--- @param src number
--- @param item string
--- @return boolean returns true if the player has the item, false otherwise.
Framework.HasItem = function(src, item)
local getCount = Framework.GetItemCount(src, item, nil)
return getCount > 0
end
-- Framework.GetPlayerInventory(src)
-- Returns the entire inventory of the player as a table.
-- returns {name = v.name, count = v.amount, metadata = v.info, slot = v.slot}
---@param src number
---@return table | nil
--- @description This will return the player's inventory as a table
--- @param src number
--- @return table | nil returns the player's inventory as a table in format: {name = v.name, count = v.amount, metadata = v.info, slot = v.slot}
Framework.GetPlayerInventory = function(src)
local xPlayer = Framework.GetPlayer(src)
if not xPlayer then return end
@@ -175,9 +174,11 @@ Framework.GetPlayerInventory = function(src)
return repackedTable
end
-- Framework.SetMetadata(src, metadata, value)
-- Adds the specified metadata key and number value to the player's data.
---@return boolean|nil
--- @description Adds the specified metadata key and number value to the player's data.
--- @param src number
--- @param metadata string
--- @param value any
--- @return boolean|nil returns true if the metadata was set successfully, otherwise it returns nil
Framework.SetPlayerMetadata = function(src, metadata, value)
local xPlayer = Framework.GetPlayer(src)
if not xPlayer then return end
@@ -186,39 +187,44 @@ Framework.SetPlayerMetadata = function(src, metadata, value)
end
-- Framework.GetMetadata(src, metadata)
-- Gets the specified metadata key to the player's data.
---@param src number
---@param metadata string
---@return any|nil
--- @description Gets the specified metadata key to the player's data.
--- @param src number
--- @param metadata string
--- @return any|nil
Framework.GetPlayerMetadata = function(src, metadata)
local xPlayer = Framework.GetPlayer(src)
if not xPlayer then return end
return xPlayer.getMeta(metadata) or false
end
-- defualt esx Available tables are
-- identifier, accounts, group, inventory, job, job_grade, loadout,
-- metadata, position, firstname, lastname, dateofbirth, sex, height,
-- skin, status, is_dead, id, disabled, last_property, created_at, last_seen,
-- phone_number, pincode
--- @description This will return the specified status column of the player.
--- @param src number
--- @param column string
--- @return string|nil
Framework.GetStatus = function(src, column)
--[[
defualt esx Available tables are:
identifier, accounts, group, inventory, job, job_grade, loadout, metadata, position,
firstname, lastname, dateofbirth, sex, height, skin, status, is_dead, id, disabled,
last_property, created_at, last_seen, phone_number, pincode
]]
local xPlayer = Framework.GetPlayer(src)
if not xPlayer then return end
return xPlayer.get(column) or nil
end
---This will return a boolean if the player is dead or in last stand.
---@param src number
---@return boolean|nil
--- @description This will return a boolean if the player is dead or in last stand
--- @param src number
--- @return boolean|nil
Framework.GetIsPlayerDead = function(src)
local xPlayer = Framework.GetPlayer(src)
if not xPlayer then return end
return xPlayer.get("is_dead") or false
end
---This will revive a player, if the player is dead or in last stand.
---@param src number
---@return boolean
--- @description This will revive a player, if the player is dead or in last stand
--- @param src number
--- @return boolean
Framework.RevivePlayer = function(src)
src = tonumber(src)
if not src then return false end
@@ -226,11 +232,10 @@ Framework.RevivePlayer = function(src)
return true
end
-- Framework.AddThirst(src, value)
-- Adds the specified value from the player's thirst level.
---@param src number
---@param value number
---@return number | nil
--- @description Adds the specified value from the player's thirst level
--- @param src number
--- @param value number
--- @return number | nil
Framework.AddThirst = function(src, value)
local clampIT = Math.Clamp(value, 0, 200000)
local levelForEsx = clampIT * 2000
@@ -238,11 +243,10 @@ Framework.AddThirst = function(src, value)
return levelForEsx
end
-- Framework.AddHunger(src, value)
-- Adds the specified value from the player's hunger level.
---@param src number
---@param value number
---@return number | nil
--- @description Adds the specified value from the player's hunger level
--- @param src number
--- @param value number
--- @return number | nil
Framework.AddHunger = function(src, value)
local clampIT = Math.Clamp(value, 0, 200000)
local levelForEsx = clampIT * 2000
@@ -250,36 +254,44 @@ Framework.AddHunger = function(src, value)
return levelForEsx
end
---This will get the hunger of a player
---@param src number
---@return number | nil
--- @description This will get the hunger of a player (ESX we get the percent of the status)
--- @param src number
--- @return number | nil
Framework.GetHunger = function(src)
local status = Framework.GetStatus(src, "status")
if not status then return 0 end
return status.hunger
if not status then return end
if type(status) ~= "table" then return end
for _, entry in ipairs(status) do
if entry.name == "hunger" then
return math.floor((entry.percent) + 0.5) or 0
end
end
end
---This will get the thirst of a player
---@param src any
---@return number | nil
--- @description This will get the thirst of a player (ESX we get the percent of the status)
--- @param src any
--- @return number | nil
Framework.GetThirst = function(src)
local status = Framework.GetStatus(src, "status")
if not status then return 0 end
return status.thirst
if not status then return nil end
if type(status) ~= "table" then return end
for _, entry in ipairs(status) do
if entry.name == "thirst" then
return math.floor((entry.percent) + 0.5) or 0
end
end
end
-- Framework.GetPlayerPhone(src)
-- Returns the phone number of the player.
---@param src number
---@return string | nil
--- @description This will get the phone number of a player
--- @param src number
--- @return string | nil return the phone number of the player
Framework.GetPlayerPhone = function(src)
local xPlayer = Framework.GetPlayer(src)
if not xPlayer then return end
return xPlayer.get("phone_number")
end
---Depricated: Returns the job name, label, grade name, and grade level of the player.
---@deprecated This will return the job name, label, grade name, and grade level of the player.
---@param src number
---@return string | nil
---@return string | nil
@@ -292,9 +304,10 @@ Framework.GetPlayerJob = function(src)
return job.name, job.label, job.grade_label, job.grade
end
---This will return the players job name, job label, job grade label job grade level, boss status, and duty status in a table
---@param src number
---@return table | nil
--- @description This will return the players job name, job label, job grade label job grade level,
--- boss status, and duty status in a table
--- @param src number
--- @return table | nil
Framework.GetPlayerJobData = function(src)
local xPlayer = Framework.GetPlayer(src)
if not xPlayer then return end
@@ -311,9 +324,9 @@ Framework.GetPlayerJobData = function(src)
}
end
---Returns the players duty status.
---@param src number
---@return boolean
--- @description This will return the players duty status, true if on duty false otherwise
--- @param src number
--- @return boolean return the players duty status
Framework.GetPlayerDuty = function(src)
local xPlayer = Framework.GetPlayer(src)
if not xPlayer then return false end
@@ -322,10 +335,10 @@ Framework.GetPlayerDuty = function(src)
return true
end
---This will toggle a players duty status
---@param src number
---@param status boolean
---@return boolean
--- @description This will toggle a players duty status
--- @param src number
--- @param status boolean
--- @return boolean
Framework.SetPlayerDuty = function(src, status)
local xPlayer = Framework.GetPlayer(src)
if not xPlayer then return false end
@@ -335,18 +348,18 @@ Framework.SetPlayerDuty = function(src, status)
return true
end
---This will get a table of player sources that have the specified job name.
---@param job string
---@return table
--- @description This will get a table of player sources that have the specified job name
--- @param job string
--- @return table
Framework.GetPlayersByJob = function(job)
return Framework.GetPlayerSourcesByJob(job) or {}
end
-- Sets the player's job to the specified name and grade.
---@param src number
---@param name string
---@param grade string
---@return nil
--- @description This will set the player's job to the specified name and grade
--- @param src number
--- @param name string
--- @param grade string
--- @return nil
Framework.SetPlayerJob = function(src, name, grade)
local xPlayer = Framework.GetPlayer(src)
if not xPlayer then return end
@@ -358,11 +371,11 @@ Framework.SetPlayerJob = function(src, name, grade)
return true
end
---This will add money based on the type of account (money/bank)
---@param src number
---@param _type string
---@param amount number
---@return boolean | nil
--- @description This will add money based on the type of account (money/bank)
--- @param src number
--- @param _type string
--- @param amount number
--- @return boolean | nil
Framework.AddAccountBalance = function(src, _type, amount)
local xPlayer = Framework.GetPlayer(src)
if not xPlayer then return end
@@ -371,11 +384,11 @@ Framework.AddAccountBalance = function(src, _type, amount)
return true
end
---This will remove money based on the type of account (money/bank)
---@param src number
---@param _type string
---@param amount number
---@return boolean | nil
--- @description This will remove money based on the type of account (money/bank)
--- @param src number
--- @param _type string
--- @param amount number
--- @return boolean | nil
Framework.RemoveAccountBalance = function(src, _type, amount)
local xPlayer = Framework.GetPlayer(src)
if not xPlayer then return end
@@ -384,10 +397,10 @@ Framework.RemoveAccountBalance = function(src, _type, amount)
return true
end
---This will remove money based on the type of account (money/bank)
---@param src number
---@param _type string
---@return string | nil
--- @description This will get the account balance based on the type of account (money/bank)
--- @param src number
--- @param _type string
--- @return string | nil
Framework.GetAccountBalance = function(src, _type)
local xPlayer = Framework.GetPlayer(src)
if not xPlayer then return end
@@ -395,14 +408,13 @@ Framework.GetAccountBalance = function(src, _type)
return xPlayer.getAccount(_type).money
end
-- Framework.AddItem(src, item, amount, slot, metadata)
-- Adds the specified item to the player's inventory.
---@param src number
---@param item string
---@param amount number
---@param slot number
---@param metadata table
---@return boolean | nil
--- @description Adds the specified item to the player's inventory
--- @param src number
--- @param item string
--- @param amount number
--- @param slot number
--- @param metadata table
--- @return boolean | nil
Framework.AddItem = function(src, item, amount, slot, metadata)
local xPlayer = Framework.GetPlayer(src)
if not xPlayer then return end
@@ -410,13 +422,12 @@ Framework.AddItem = function(src, item, amount, slot, metadata)
return true
end
-- Framework.RemoveItem(src, item, amount, slot, metadata)
-- Removes the specified item from the player's inventory.
---@param src number
---@param item string
---@param amount number
---@param slot number
---@param metadata table
--- @description Removes the specified item from the player's inventory
--- @param src number
--- @param item string
--- @param amount number
--- @param slot number
--- @param metadata table
---@return boolean | nil
Framework.RemoveItem = function(src, item, amount, slot, metadata)
local xPlayer = Framework.GetPlayer(src)
@@ -425,9 +436,9 @@ Framework.RemoveItem = function(src, item, amount, slot, metadata)
return true
end
---This will get all owned vehicles for the player
---@param src number
---@return table
--- @description This will get all owned vehicles for the player
--- @param src number
--- @return table
Framework.GetOwnedVehicles = function(src)
local citizenId = Framework.GetPlayerIdentifier(src)
local result = MySQL.Sync.fetchAll("SELECT vehicle, plate FROM owned_vehicles WHERE owner = '" .. citizenId .. "'")
@@ -441,11 +452,9 @@ Framework.GetOwnedVehicles = function(src)
return vehicles
end
-- Framework.RegisterUsableItem(item, cb)
-- Registers a usable item with a callback function.
---@param itemName string
---@param cb function
--- @description Registers a usable item with a callback function
--- @param itemName string
--- @param cb function
Framework.RegisterUsableItem = function(itemName, cb)
local func = function(src, item, itemData)
itemData = itemData or item
@@ -459,6 +468,9 @@ end
RegisterNetEvent("esx:playerLoaded", function(src)
src = src or source
TriggerEvent("community_bridge:Server:OnPlayerLoaded", src)
local jobData = Framework.GetPlayerJobData(src)
if not jobData then return end
Framework.AddJobCount(src, jobData.jobName)
end)
RegisterNetEvent("esx:playerLogout", function(src)
+20
View File
@@ -14,6 +14,12 @@ Framework.GetFrameworkName = function()
return 'qb-core'
end
---This will get the name of the in use resource.
---@return string
Framework.GetResourceName = function()
return 'qb-core'
end
---This will return true if the player is loaded, false otherwise.
---This could be useful in scripts that rely on player loaded events and offer a debug mode to hit this function.
---@return boolean
@@ -109,6 +115,20 @@ Framework.GetItemInfo = function(item)
return repackedTable
end
---This will get the hunger of a player
---@return number
Framework.GetHunger = function()
local hunger = Framework.GetPlayerMetaData("hunger") or 0
return math.floor((hunger) + 0.5) or 0
end
---This will get the thirst of a player
---@return number
Framework.GetThirst = function()
local thirst = Framework.GetPlayerMetaData("thirst") or 0
return math.floor((thirst) + 0.5) or 0
end
---This will get the players identifier (citizenid) etc.
---@return string
Framework.GetPlayerIdentifier = function()
Loaded 100 of 204 files, more files were not shown because too many files have changed in this diff. Show more