> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dkscripts.com.br/llms.txt
> Use this file to discover all available pages before exploring further.

# Funções em Client

# Funções e Validações em Client do Trunkin

Nesta seção, vamos detalhar as principais funções que compõem a lógica do **Trunkin**. Essas funções são responsáveis por validar as condições para que o jogador possa acessar ou sair do porta-malas, bloquear controles durante o uso e gerenciar permissões com base no estado do veículo e do jogador.

<Note>
  📁 dk\_trunkin > config > client > functions.lua
</Note>

***

## 1. Verificação do Estado do Veículo

### **isUnlocked**

Verifica se o veículo está destrancado.
**Retorno:** `true` se o veículo estiver destrancado, `false` caso contrário.

```lua dk_trunkin/config/client/functions.lua theme={null}
---@param vehEntity number
---@return boolean
local function isUnlocked(vehEntity)
    return not (GetVehicleDoorLockStatus(vehEntity) ~= 1)
end
```

### **isVehicleAllowed**

Filtra o veículo com base no modelo e na classe.

* Se o modelo estiver na lista de `disabledModelTrunk`, o acesso é negado.
* Se a classe do veículo estiver bloqueada em `blockedClasses`, o acesso também é negado.

```lua dk_trunkin/config/client/functions.lua theme={null}
---@param vehEntity number
---@return boolean
local function isVehicleAllowed(vehEntity)
    if Config.disabledModelTrunk[GetEntityModel(vehEntity)] then
        return false
    end

    if Config.blockedClasses[GetVehicleClass(vehEntity)] then
        return false
    end

    return true
end
```

***

## 2. Bloqueio de Controles

A função `blockControls` desativa uma série de controles enquanto o jogador está dentro do porta-malas. Isso impede ações indesejadas que poderiam interferir na experiência ou causar conflitos com outras funcionalidades.

```lua dk_trunkin/config/client/functions.lua theme={null}
function Config.functions.blockControls()
    DisableControlAction(1,73,true)
    DisableControlAction(1,23,true)
    DisableControlAction(1,29,true)
    DisableControlAction(1,47,true)
    DisableControlAction(1,187,true)
    DisableControlAction(1,189,true)
    DisableControlAction(1,190,true)
    DisableControlAction(1,188,true)
    DisableControlAction(1,311,true)
    DisableControlAction(1,245,true)
    DisableControlAction(1,257,true)
    DisableControlAction(1,167,true)
    DisableControlAction(1,140,true)
    DisableControlAction(1,141,true)
    DisableControlAction(1,142,true)
    DisableControlAction(1,137,true)
    DisableControlAction(1,37,true)
end
```

***

## 3. Gerenciamento de Permissões para Acesso

### **toggleTrunkPermission**

Verifica se o jogador pode entrar ou sair do porta-malas, levando em consideração diversos fatores:

* Estado do jogador (morto ou no modo sequestro).
* Existência do porta-malas (verificando os ossos "boot" e "bonnet" ou a presença de um offset customizado).
* Estado do veículo (motor, integridade e se está na água).
* Se o veículo está destrancado e permitido pela filtragem.

Se alguma condição falhar, uma notificação é exibida, e a função retorna `false`.

```lua dk_trunkin/config/client/functions.lua theme={null}
---@param entering boolean
---@param vehEntity number
---@param kidnapped boolean
---@return boolean
function Config.functions.toggleTrunkPermission(entering, vehEntity, kidnapped)
    local ped = PlayerPedId()
    if not kidnapped and GetEntityHealth(ped) <= 101 then
        DkNotify("red", Locale("disabled_dead"))
        return false
    end
    if IsPedInAnyVehicle(ped) or GetVehiclePedIsEntering(ped) ~= 0 then
        DkNotify("red", Locale("disabled_inside_veh"))
        return false
    end

    if entering then
        local boot = GetEntityBoneIndexByName(vehEntity,"boot")
        local bonnet = GetEntityBoneIndexByName(vehEntity,"bonnet")
        if boot == -1 and bonnet == -1 and not Config.customOffsets[GetEntityModel(vehEntity)] then
            DkNotify("red", Locale("veh_has_no_trunk"))
            return false
        end

        if GetVehicleEngineHealth(vehEntity) <= 0 or IsEntityInWater(vehEntity) then
            DkNotify("red", Locale("veh_destroyed"))
            return false
        end

        if not isUnlocked(vehEntity) then
            DkNotify("red", Locale("locked_veh"))
            return false
        end

        if not isVehicleAllowed(vehEntity) then
            DkNotify("red", Locale("veh_blocked"))
            return false
        end
    end

    return true
end
```

***

## 4. Ações ao Entrar e Sair do Porta-malas

As funções a seguir são acionadas quando o jogador entra ou sai do porta-malas.\
Você pode personalizar essas funções para adicionar estados ou executar ações adicionais (como invisibilidade ou alteração de comandos).

### **onEnterTrunk**

Executada ao entrar no porta-malas.\
Exemplo: Marcar o estado do jogador como "dentro do porta-malas".

```lua dk_trunkin/config/client/functions.lua theme={null}
---@param vehEntity number
---@param kidnapped boolean
function Config.functions.onEnterTrunk(vehEntity, kidnapped)
    -- Normalmente utilizadas em creative
    LocalPlayer["state"]["Invisible"] = true
    LocalPlayer["state"]["Commands"] = true
    
    -- LocalPlayer["state"]["inTrunk"] = true
end
```

### **onLeaveTrunk**

Executada ao sair do porta-malas.\
Exemplo: Restaurar o estado do jogador para "fora do porta-malas".

```lua dk_trunkin/config/client/functions.lua theme={null}
---@param vehEntity number
---@param kidnapped boolean
function Config.functions.onLeaveTrunk(vehEntity, kidnapped)
    -- Normalmente utilizadas em creative
    LocalPlayer["state"]["Invisible"] = false
    LocalPlayer["state"]["Commands"] = false

    -- LocalPlayer["state"]["inTrunk"] = false
end
```

***

🔔 **Resumo:**

* **Validações:** As funções `isUnlocked` e `isVehicleAllowed` garantem que o veículo esteja em condições de uso.
* **Controle de Ação:** `blockControls` impede que o jogador realize ações indesejadas enquanto está no porta-malas.
* **Permissões:** `toggleTrunkPermission` checa diversas condições para permitir o acesso seguro e adequado.
* **Estados do Jogador:** `onEnterTrunk` e `onLeaveTrunk` permitem a customização dos estados do jogador ao interagir com o porta-malas.

Essas funções são fundamentais para o funcionamento do **Trunkin** e podem ser adaptadas conforme as necessidades do seu servidor. Personalize-as para aprimorar a experiência do jogador e garantir um controle mais refinado durante a interação com o porta-malas.
