# Looting System

## Table of Contents

1. [Overview](#overview)
2. [Features](#features)
3. [Installation](#installation)
4. [Configuration](#configuration)
5. [Clothing System](#clothing-system)
6. [Framework Support](#framework-support)
7. [UI Systems](#ui-systems)
8. [Logging System](#logging-system)
9. [API Reference](#api-reference)
10. [Troubleshooting](#troubleshooting)

## Overview

Hate Looting is an advanced looting system for FiveM servers that supports both QBCore and ESX frameworks. It provides a comprehensive solution for searching objects, looting NPCs, and managing inventory with advanced clothing metadata generation and Discord logging integration.

### Key Highlights

* **Dual Framework Support**: Works with both QBCore and ESX
* **Advanced Clothing System**: Automatic metadata generation with blacklist support
* **Multiple UI Options**: Built-in UI or core\_inventory integration
* **Discord Integration**: Rich logging with inventory images
* **Performance Optimized**: Client-side detection and caching systems
* **Highly Configurable**: Extensive configuration options

## Features

### Core Features

* **Object Looting**: Search various props and objects in the game world
* **NPC/Animal Looting**: Loot zombies, animals, and other NPCs
* **Progress Bar Integration**: Support for multiple progress bar systems
* **Target System**: Integration with ox\_target, qb-target, and qtarget
* **Inventory Integration**: Works with ox\_inventory and core\_inventory
* **Anti-Exploit**: Distance checks and search state management

### Advanced Features

* **Clothing Metadata System**: Automatic generation of clothing metadata for core\_inventory
* **Client-Side Detection**: Dynamic max value detection for clothing variations
* **Blacklist System**: Exclude specific clothing models from generation
* **Unique Item Identification**: Prevents UI selection issues with duplicate items
* **Discord Logging**: Rich webhook logging with inventory images
* **Loot Zones**: Configurable loot increase/decrease zones
* **Item Requirements**: Require specific items or weapons for certain loot types

### UI Features

* **Dual UI System**: Choose between built-in UI or core\_inventory
* **Responsive Design**: Mobile-friendly interface
* **Sound Effects**: Audio feedback for looting actions
* **Visual Feedback**: Progress indicators and animations
* **Inventory Images**: Display item images from inventory system

## Installation

### Requirements

* **Framework**: QBCore or ESX
* **Dependencies** (Optional):
  * ox\_lib
  * mythic\_progbar / esx\_progressbar
  * ox\_target / qb-target / qtarget
  * ox\_inventory / core\_inventory

### Steps

1. **Download**: Extract `hate-looting` to your resources folder
2. **Server Config**: Add `ensure hate-looting` to your server.cfg
3. **Framework Detection**: The script auto-detects your framework
4. **Configure**: Edit configuration files as needed
5. **Start Server**: Restart your server

## Configuration

### Main Config (config.lua)

#### Basic Settings

```lua
Config.PedDeleteTime = 10 -- Time in seconds after which looted ped will be deleted
Config.TargetDistance = 4.0 -- Distance to target peds/objects
Config.animalLoot = true -- Enable animal looting
Config.enableZombieLoot = true -- Enable zombie looting
Config.Debug = false -- Enable debug mode
Config.lootRefreshTime = 30 -- Default refresh time for prop loot (minutes)
Config.emptyLootRefreshTime = 5 -- Empty loot location refresh time (minutes)
```

#### UI Configuration

```lua
Config.UseUIType = "ownui" -- "ownui" or "core_inventory"
Config.UseProgressBar = true -- Use progress bar
Config.UsePressE = false -- Use press E to loot instead of target system
Config.DistanceCheckProtection = 25.0 -- Security distance check
Config.InventoryImagePath = "nui://core_inventory/html/img/" -- Image path for inventory items
```

### Clothing Configuration (clothing\_config.lua)

#### Clothing Metadata System

```lua
Config.useCoreMetadataClothes = true -- Enable clothing metadata generation
```

#### Clothing Item Configuration

```lua
Config.ClothesConfig = {
    torso = {
        componentId = 11,
        propId = nil,
        maxModel = 500,
        maxTexture = 0,
        autoDetectMax = true -- Enable auto-detection for max values
    },
    -- ... other clothing items
}
```

#### Blacklist System

```lua
Config.ClothingBlacklist = {
    torso = {1, 2, 3, 15}, -- Exclude these model IDs
    pants = {0, 1},
    shoes = {},
    -- ... other clothing items
}
```

#### Torso Mappings

The script includes comprehensive torso mappings for proper clothing compatibility:

```lua
Config.TorsoMappings = {
    male = {
        [0] = {0, 1, 9, 16, 271, 345, ...}, -- Model mappings for torso 0
        [1] = {529, 6, 165, 397, ...}, -- Model mappings for torso 1
        -- ... extensive mappings
    },
    female = {
        -- Female-specific mappings (expandable)
    }
}
```

### Loot Rewards Configuration

#### Loot Tables

```lua
Config.LootRewards = {
    ["zombie_default"] = {
        loop = 1, -- Number of loot rolls
        loopIncrease = nil, -- Additional rolls from zones
        {name = {'torso','pants','shoes'}, min = 1, max = 3, chance = 10},
        {name = {'field_dressing','packing_bandage'}, min = 1, max = 3, chance = 5},
        -- ... more loot entries
    },
    -- ... more loot types
}
```

#### Lootable Objects

```lua
Config.LootAbles = {
    ['prop_dumpster_3a'] = "trashBig",
    ['prop_gas_pump_old2'] = "benzin",
    ['prop_toolchest_01'] = "vehparts",
    -- ... extensive object list
}
```

#### Animal/NPC Loot Types

```lua
Config.lootByHashType = {
    ['a_c_boar'] = 'pig_loot',
    ['a_c_cat_01'] = 'cat_loot',
    ['a_c_deer'] = 'deer_loot',
    -- ... animal mappings
}
```

### Advanced Configuration

#### Loot Zones

```lua
Config.lootIncreaseZones = {
    {coords = vector3(215.578, -1135.859, 29.29675), radious = 400.0, loopIncrease = 2}
}

Config.disableLootZones = {
    {coords = vector3(215.578, -1135.859, 29.29675), radius = 400.0}
}
```

#### Item/Weapon Requirements

```lua
Config.lootTypeItemNeeded = {
    ['gunloot'] = {items = {"blowtorch"}, remove = true},
    ['pistolCase'] = {items = {"blowtorch"}, remove = true}
}

Config.lootTypeWeaponNeeded = {
    ['pig_loot'] = {
        weapons = {"weapon_knife", "weapon_hatchet"}, 
        label = "You need a cutting weapon"
    }
}
```

#### Progress Bar Animations

```lua
Config.ProgressBars = {
    ["zombie_default"] = {
        duration = 1000,
        label = "Searching Corpse",
        animation = {
            animDict = 'amb@prop_human_bum_bin@base',
            anim = 'base'
        }
    },
    -- ... more progress bar configs
}
```

## Clothing System

### Overview

The clothing system automatically generates metadata for clothing items when using core\_inventory, ensuring compatibility with clothing systems.

### Features

* **Auto-Detection**: Automatically detects maximum model and texture variations
* **Blacklist Support**: Exclude problematic clothing models
* **Gender Support**: Separate configurations for male/female characters
* **Torso Mapping**: Proper torso compatibility for clothing items
* **Caching System**: Client-side caching for performance optimization

### Configuration Examples

#### Basic Clothing Item

```lua
mask = {
    componentId = 1,
    propId = nil,
    maxModel = 200,
    maxTexture = 0,
    autoDetectMax = true
}
```

#### Prop Item (Hat/Glasses)

```lua
hat = {
    componentId = nil,
    propId = 0,
    maxModel = 200,
    maxTexture = 0,
    autoDetectMax = true
}
```

#### Blacklisting Models

```lua
Config.ClothingBlacklist = {
    mask = {1, 5, 10, 25}, -- These mask models will never be generated
    hat = {0, 3, 7}
}
```

### Metadata Generation

The system generates metadata in the following format:

```lua
-- For component items (torso, pants, etc.)
{
    mModel = 15,
    mTexture = 2,
    mID = 11,
    mTorso = 1, -- For torso items
    image = 'male_11_15',
    mModelMax = 500,
    wModelMax = 500
}

-- For prop items (hat, glasses, etc.)
{
    mPropModel = 10,
    mPropTexture = 1,
    mPropID = 0,
    image = 'male_prop_0_10',
    mModelMax = 200,
    wModelMax = 200
}
```

## Framework Support

### Unified Framework System

The script uses a unified framework file (`server/framework_unified.lua`) that supports both QBCore and ESX with automatic detection.

### Auto-Detection

```lua
if GetResourceState('es_extended') ~= 'missing' then
    Config.Framework = "ESX"
elseif GetResourceState('qb-core') ~= 'missing' then
    Config.Framework = "QB"
end
```

### Framework Functions

The unified system provides consistent functions:

* `GetPlayerFromId(src)` - Get player object
* `AddInventoryItem(player, item, count, metadata)` - Add item to inventory
* `RemoveInventoryItem(player, item, count)` - Remove item from inventory
* `HasEnoughtInventoryItem(player, item, count)` - Check item availability
* `GetItemLabel(item)` - Get item display name
* `ShowNotification(src, message)` - Send notification

## UI Systems

### Built-in UI System

The script includes a custom HTML/CSS/JavaScript UI with the following features:

#### Features

* **Responsive Design**: Works on all screen sizes
* **Sound Effects**: Audio feedback for actions
* **Animations**: Smooth transitions and effects
* **Item Images**: Display inventory item images
* **Drag and Drop**: Interactive item management

#### Customization

The UI can be customized by editing files in the `html/` folder:

* `nui.html` - HTML structure
* `app.js` - JavaScript functionality
* Sound files for audio feedback

### Core Inventory Integration

When using core\_inventory, the script integrates seamlessly:

```lua
Config.UseUIType = "core_inventory"
```

Features:

* **Advanced Loot Interface**: Uses core\_inventory's openLootAdvanced
* **Metadata Support**: Full metadata preservation
* **Inventory Management**: Integrated with core\_inventory systems

## Logging System

### Discord Webhook Integration

The script includes comprehensive Discord logging with the following features:

#### Log Types

* **Loot Events**: When players loot items
* **Admin Actions**: Administrative activities
* **Error Logging**: System errors and issues

#### Configuration (logs.lua)

```lua
Config.Webhooks = {
    ['loot'] = 'YOUR_DISCORD_WEBHOOK_URL',
    ['admin'] = 'YOUR_ADMIN_WEBHOOK_URL'
}
```

#### Features

* **Rich Embeds**: Detailed Discord embeds with colors and fields
* **Item Images**: Display inventory item images in logs
* **Metadata Logging**: Log item metadata for debugging
* **Player Information**: Include player details and coordinates
* **Timestamp Support**: Automatic timestamp generation

#### Example Log Entry

```json
{
    "title": "Player Looted Items",
    "color": 3447003,
    "fields": [
        {"name": "Player", "value": "PlayerName (123)", "inline": true},
        {"name": "Item", "value": "torso x2", "inline": true},
        {"name": "Source", "value": "zombie_default", "inline": true},
        {"name": "Coordinates", "value": "123.45, 456.78, 789.01", "inline": true}
    ],
    "thumbnail": {"url": "inventory_item_image_url"},
    "timestamp": "2025-08-03T12:00:00.000Z"
}
```

## API Reference

### Server Events

#### Core Events

```lua
-- Start looting process
TriggerServerEvent('server:PropLoot', coords, model, k, prop)
TriggerServerEvent('server:PedLoot', coords, entityModel, model, k)

-- Take specific loot item
TriggerServerEvent('server:TakeLoot', lootId, itemName, count, uniqueId)

-- Search state management
TriggerServerEvent('server:StartLoot', coords)
TriggerServerEvent('server:StopLoot', coords)
```

#### Clothing System Events

```lua
-- Request max clothing values from client
TriggerClientEvent('server:requestClothingMaxValues', src, itemName, config)

-- Receive max values from client
TriggerServerEvent('client:responseClothingMaxValues', itemName, maxModel, maxTexture)
```

### Client Events

#### UI Events

```lua
-- Show loot interface
TriggerClientEvent('showLootUI', src, lootData)

-- Update loot interface
TriggerClientEvent('updateLootUI', -1, updateData)

-- Delete NPC after looting
TriggerClientEvent('deleteped', -1, entityId)
```

### Server Functions

#### Clothing Functions

```lua
-- Generate clothing metadata
generateClothingMetadata(itemName, src)

-- Check if item is clothing
isClothingItem(itemName)

-- Get torso mapping for model
GetTorsoForModel(mModel, gender)

-- Preload clothing max values
preloadClothingMaxValues(src)
```

#### Utility Functions

```lua
-- Generate random number for loot ID
returnRandomNumber()

-- Round coordinates for consistency
roundCoords(coords)

-- Find entity in loot table
findEntityInTable(entity, coords, model)

-- Get loop increase from zones
GetLoopAdd(lootType, coords)
```

### Client Functions

#### Clothing Detection

```lua
-- Get max clothing variations
GetClothingMaxValues(clothesConfig)

-- Check required weapons
HasRequiredWeapon(lootType)
```

#### UI Management

```lua
-- NUI Callbacks
RegisterNUICallback('takeLoot', function(data, cb))
RegisterNUICallback('closeInventory', function(data, cb))
```

## Troubleshooting

### Common Issues

#### 1. Clothing Metadata Not Working

**Problem**: Clothing items don't have proper metadata **Solution**:

* Ensure `Config.useCoreMetadataClothes = true`
* Verify core\_inventory is installed and working
* Check if clothing items are properly configured in `clothing_config.lua`

#### 2. UI Not Showing

**Problem**: Loot UI doesn't appear **Solution**:

* Check `Config.UseUIType` setting
* Verify NUI resource is properly started
* Check for JavaScript errors in console (F8)

#### 3. Framework Detection Issues

**Problem**: Script doesn't detect framework **Solution**:

* Ensure framework resource is started before hate-looting
* Check framework resource names match expected names
* Verify framework is properly installed

#### 4. Loot Not Refreshing

**Problem**: Loot locations don't refresh **Solution**:

* Check `Config.lootRefreshTime` and `Config.emptyLootRefreshTime`
* Verify server isn't restarting before refresh time
* Check for errors in server console

#### 5. Distance/Target Issues

**Problem**: Can't target objects or distance issues **Solution**:

* Adjust `Config.TargetDistance`
* Check target system integration (ox\_target, qb-target)
* Verify `Config.DistanceCheckProtection` isn't too restrictive

### Debug Mode

Enable debug mode for troubleshooting:

```lua
Config.Debug = true
```

This will provide console output for:

* Loot generation processes
* Clothing metadata generation
* Framework detection
* Target system interactions

### Performance Optimization

#### Client-Side Caching

The script uses client-side caching for clothing max values to reduce server load:

* Cache duration: 5 minutes
* Automatic cache refresh
* Fallback to config values if detection fails

#### Server-Side Optimization

* Unified framework system reduces code duplication
* Efficient loot generation algorithms
* Optimized database queries (if applicable)

### Error Logging

The script includes comprehensive error logging:

* Server console errors
* Client console errors (when debug enabled)
* Discord webhook error notifications
* Fallback systems for critical failures

## Support

For additional support:

1. Check this documentation first
2. Enable debug mode to identify issues
3. Check server/client console for errors
4. Verify all dependencies are properly installed
5. Ensure proper configuration of all systems

##

***

*This documentation covers the complete feature set of Hate Looting. For the most up-to-date information, always refer to the latest version of this documentation.*


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hate-development.gitbook.io/hate-development-docs/apocalyptic-scripts/looting-system.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
