# Metabolism System

## CAS Metabolism - Configuration & Exports Guide

### Table of Contents

1. Configuration Files
   * Client Config
   * Server Config
   * Shared Config
   * Item Configuration
2. Client Exports
3. Server Exports

***

### Configuration Files

#### Client Config

**File:** `config/client_config.lua`

**Basic Settings**

```lua
Config.SettingsMenuCommand = "hudsettings"
```

Command to open the HUD settings menu.

```lua
Config.HudVisibleCommand = "hudvisible"
```

Command to toggle HUD visibility on/off.

```lua
Config.ShowHUDWhileSprintCommand = "hudshowsprint"
```

Command to show HUD while sprinting.

```lua
Config.VoiceSystem = "pma"
```

Voice system for microphone display. Options: `"pma"`, `"salty"`, `"mumble"`, `"auto"`

```lua
Config.Notification = "cas-simplenotify"
```

Notification system to use. Options: `"cas-simplenotify"`, `"cas-notification"`, `"vorp"`, `"rsg"`

```lua
Config.UseCASProgressBar = true
```

Use CAS progress bar for item consumption animations.

```lua
Config.MaxHealth = 600
```

Maximum health value (framework dependent). Used for health bar calculations.

```lua
Config.DefaultHudTheme = "western"
```

Default HUD theme for new players. Options: `"western"`, `"minimal"`, `"wave"`

***

**Metabolism Decay Settings**

```lua
Config.HungerDecreaseTimer = 10
Config.HungerDecreaseAmount = 0.4
```

Base hunger decrease: Every **10 seconds**, hunger decreases by **0.4%** (idle/walking).

```lua
Config.ThirstDecreaseTimer = 15
Config.ThirstDecreaseAmount = 0.4
```

Base thirst decrease: Every **15 seconds**, thirst decreases by **0.4%** (idle/walking).

```lua
Config.Running = {
    HungerDecreaseTimer = 5,
    HungerDecreaseAmount = 0.8,
    ThirstDecreaseTimer = 7,
    ThirstDecreaseAmount = 0.8,
}
```

Increased decay rates while running/sprinting.

```lua
Config.DecreaseValuesWhileAfk = false
```

Set to `true` to continue decreasing stats while player is AFK.

***

**Activity Multipliers**

```lua
Config.ActivityMultipliers = {
    idle   = { hunger = 0.05, thirst = 0.07 },
    walk   = { hunger = 0.10, thirst = 0.20 },
    run    = { hunger = 0.15, thirst = 0.20 },
    sprint = { hunger = 0.15, thirst = 0.20 },
    coast  = { hunger = 0.15, thirst = 0.20 },
    swim   = { hunger = 0.15, thirst = 0.20 },
    mounted = { hunger = 0.08, thirst = 0.08 }
}
```

Multipliers for hunger/thirst decay based on player activity.

* **idle**: Barely moving
* **walk**: Walking speed
* **run**: Jogging
* **sprint**: Full sprint
* **coast**: Standing still
* **swim**: Swimming
* **mounted**: On horseback

***

**Starvation & Dehydration**

```lua
Config.StarvationDamageDelay = 120.0
```

Seconds to wait after both hunger and thirst reach 0 before health damage starts. Set to `0` to disable.

```lua
Config.StarvationDamageInterval = 10.0
```

Seconds between health damage ticks when starving/dehydrated.

```lua
Config.StarvationDamageAmount = 20
```

Health points removed per tick when starving. Set to `0` to disable damage.

***

**Stress System**

```lua
Config.EnableStressSytem = true
```

Enable/disable the stress system.

```lua
Config.EnableShakeEffectForStress = true
```

Enable screen shake effect when stress is high.

```lua
Config.StressSettings = {
    enabled = true,

    -- Speed-based stress
    minimumSpeedMph = 35.0,
    speedCheckIntervalMs = 2000,
    speedStressMin = 1,
    speedStressMax = 3,

    -- Shooting stress
    shootingEnabled = true,
    shootingCheckIntervalMs = 250,
    shootingStressChance = 0.25,
    shootingStressMin = 1,
    shootingStressMax = 3,

    -- Visual effects
    effectMinimumSeverity = 25.0,
    effectCooldownMs = 3000,
    ragdollSeverity = 85.0,
    ragdollCooldownMs = 7000,
    shakeIntensityMin = 0.05,
    shakeIntensityMax = 0.35,

    -- Health damage from stress
    damageEnabled = true,
    damageSeverityThreshold = 85.0,
    damageDelayMinutes = 60.0,
    damageTickIntervalMs = 15000,
    damageAmount = 3
}
```

**Settings explained:**

* `minimumSpeedMph`: Speed (MPH) needed to start gaining stress from travel
* `speedStressMin/Max`: Random stress amount added per check
* `shootingStressChance`: Probability (0.0-1.0) of gaining stress when shooting
* `effectMinimumSeverity`: Stress % when visual effects start
* `shakeIntensityMin/Max`: Screen shake strength range
* `damageSeverityThreshold`: Stress % when health damage begins
* `damageDelayMinutes`: Time before damage starts at high stress
* `damageAmount`: HP removed per tick

***

**Sleep System**

```lua
Config.SleepSettings = {
    enabled = true,
    maxValue = 100,
    updateIntervalMs = 1000,

    gainPerMinute = {
        idle = 3.0,
        coast = 3.5,
        walk = 4.0,
        run = 5.0,
        sprint = 6.0,
        mounted = 4.5,
        swim = 5.5
    },

    modifiers = {
        drunkAbove = 65,
        drunkGainMult = 1.20,
        lowNeedThreshold = 15,
        lowNeedGainMult = 1.15
    },

    drowsy = {
        startAt = 90,
        useDownedFx = false,
        blinkFx = "1p_maskdark",
        blinkEveryMsMin = 9000,
        blinkEveryMsMax = 17000,
        blinkDurationMs = 2500
    },

    microsleep = {
        startAt = 95,
        cooldownMs = 12000,
        chanceAt95 = 0.05,
        chanceAt98 = 0.10,
        blackoutMsMin = 450,
        blackoutMsMax = 1100
    },

    knockout = {
        startAt = 99,
        checkEveryMs = 2500,
        chanceAt99 = 0.08,
        chanceAt100 = 0.18,
        resistWindowMs = 8500,
        resistChanceMult = 0.40,
        resistExtraGainPerTick = 0.20,
        ragdollMs = 4500,
        fadeOutMs = 1200,
        blackScreenMs = 2500,
        fewHoursFx = "Title_Gen_FewHoursLater",
        fewHoursFxMs = 3000,
        fadeInMs = 2000,
        wakeFx = "PlayerWakeUpInterrogation",
        wakeFxMs = 17000,
        setSleepTo = 45,
        staminaCoreAdd = 18
    },

    beds = {
        enabled = true,
        searchRadius = 2.2,
        promptHoldMs = 800,
        promptControl = 0xCEFD9220,
        defaultSleepSeconds = 25,
        minSleepSeconds = 10,
        maxSleepSeconds = 80,
        reducePerSecond = 1.2,
        fewHoursFx = "Title_Gen_FewHoursLater",
        fewHoursFxMs = 3000,
        wakeFx = "PlayerWakeUpInterrogation",
        wakeFxMs = 15000,
        fadeOutMs = 900,
        fadeInMs = 900,
        entries = {
            {
                scenario = "WORLD_HUMAN_SLEEP_GROUND_ARM",
                models = { "p_bedrollopen01x" },
                offset = { x = 0.0, y = 0.0, z = 1.0, h = 0.0 }
            }
        }
    }
}
```

**Sleep Settings:**

* `gainPerMinute`: How fast sleep accumulates per activity type (higher = faster fatigue)
* `drunkGainMult`: Sleep builds 20% faster when drunk above threshold
* `lowNeedGainMult`: Sleep builds 15% faster when hunger/thirst below threshold
* `drowsy.startAt`: Sleep % when blinking effects start (90%)
* `microsleep.startAt`: Sleep % when brief blackouts can occur (95%)
* `knockout.startAt`: Sleep % when full knockout is possible (99%)
* `beds.reducePerSecond`: How much sleep decreases per second when sleeping in bed
* `beds.entries`: Add bed/bedroll models where players can sleep

***

**Cleanliness System**

```lua
Config.Cleanliness = {
    Enabled = true,
    MinCleanPercent = 25,
    WarningIntervalSeconds = 60,
    WarningText = "You're very dirty! You need to wash.",
    WarningDurationMs = 6000,
    PenaltyIntervalSeconds = 10,
    DamagePerTick = 4,
    DoFx = true
}
```

* `MinCleanPercent`: Cleanliness % threshold for warnings
* `PenaltyIntervalSeconds`: Damage frequency when too dirty
* `DamagePerTick`: HP damage per tick
* `DoFx`: Apply visual dirt effects

***

**Temperature System**

```lua
Config.MinTemp = -2.0
Config.MaxTemp = 35.0
```

Temperature range in Celsius.

```lua
Config.RemoveHealth = 3
```

Health damage from extreme temperatures.

```lua
Config.TempWarningCooldown = 10.0
```

Seconds between temperature warnings.

```lua
Config.HotTempThirstDrain = 0.15
```

Extra thirst drain in hot weather.

```lua
Config.InteriorTempBalance = {
    enabled = true,
    comfortTemp = 20.0,
    maxShift = 12.0
}
```

Indoors temperature adjustment toward comfortable level.

```lua
Config.CampfireWarmth = {
    enabled = true,
    radius = 6.0,
    maxBonus = 10.0,
    onlyWhenCold = false,
    coldBelow = 15.0,
    models = {
        "p_campfirecombined01x",
        "p_campfirecombined02x",
        "p_campfire02x",
        "p_campfire03x",
        "p_cookfire01x"
    }
}
```

Warmth bonus from nearby campfires.

***

**Intoxication System**

```lua
Config.walkingStylesByDrunk = {
    mild = {
        {"default", "slightly_drunk"},
        {"normal_town", "slightly drunk"},
    },
    medium = {
        {"default", "moderate_drunk"},
        {"murfree", "moderate_drunk"},
    },
    high = {
        {"default", "very_drunk"},
        {"lost_man_normal", "very_drunk"},
    }
}
```

Walking styles applied at different drunk levels.

```lua
Config.Vomit = {
    cooldownMs = 6000,
    staminaDrainDurationMs = 12000,
    staminaDrainTickMs = 750,
    staminaCoreLossPerTick = 2,
    applyStomachEmptyingOnAlcoholVomit = false,
    emptyHungerOnVomit = 20,
    emptyThirstOnVomit = 20,
    notifyText = "You vomit."
}
```

Vomiting system when too drunk or overeating/drinking.

```lua
Config.OverConsume = {
    enabled = true,
    maxNeedValue = 100,
    warnCooldownMs = 8000,
    chainWindowMs = 12000,
    triesToVomit = 2,
    overeatText = "You are overeating!",
    overdrinkText = "You are overdrinking!",
    vomitText = "You vomit.",
    emptyHungerOnVomit = 35,
    emptyThirstOnVomit = 35,
    staminaDrainDurationMs = 12000,
    staminaDrainTickMs = 750,
    staminaCoreLossPerTick = 10
}
```

Prevents overeating/overdrinking. After `triesToVomit` attempts, player vomits.

***

**HUD Colors**

```lua
Config.HudColors = {
    stamina = "#918D2A",
    hunger = "#91552A",
    thirst = "#2A8491",
    stress = "#7E7E7E",
    dirt = "#7E7E7E",
    health = "#B13535",
    microphone = "#B135AE",
    weather = "#B135AE",
    sleep = "#4B0082",
    drunk = "#35B177",
    horsehealth = "#7E7E7E",
    horsestamina = "#B19E35",
    levelprogress = "#DAA520"
}
```

Default HUD element colors (hex format).

***

**Color Presets**

```lua
Config.ColorPresets = {
    default = { ... },
    neon = { ... },
    nature = { ... },
    fire = { ... },
    ice = { ... },
    gamedefault = { ... }
}
```

Pre-made color themes players can select. Each preset contains:

* `hudColors`: Progress bar colors
* `iconColors`: Icon colors when full
* `emptyIconColors`: Icon colors when empty

***

**Minimap Styles**

```lua
Config.MinimapStyles = {
    ["style1"] = {
        name = "Hide Map",
        description = "Hide the minimap."
    },
    ["style2"] = {
        name = "Square Modern",
        description = "Modern square minimap with rounded corners"
    },
    ["style3"] = {
        name = "Hexagonal",
        description = "Western-style hexagonal minimap design"
    },
    ["style4"] = {
        name = "Vintage",
        description = "Old-school vintage map with aged borders"
    }
}
```

Available minimap style options.

***

**Warning & Need Decay**

```lua
Config.NeedsDecayStartDelay = 300.0
```

Seconds to wait before decay begins after refilling hunger/thirst (5 minutes grace period).

```lua
Config.NeedWarningThreshold = 10.0
```

Hunger/thirst % at which warnings trigger.

```lua
Config.NeedWarningInterval = 120.0
```

Seconds between repeated warnings.

***

#### Server Config

**File:** `config/server_config.lua`

```lua
Config.Database = {
    Enabled = true,
    Table = "cas_metabolism",
    SaveIntervalMs = 60000,
    AlsoSyncFramework = true,
    UseCharacterIdentifier = true,
    Debug = false
}
```

**Settings:**

* `Enabled`: Enable MySQL database persistence
* `Table`: Database table name
* `SaveIntervalMs`: How often to save data (60000ms = 1 minute)
* `AlsoSyncFramework`: Also update framework's status system for compatibility
* `UseCharacterIdentifier`: Use character-specific storage (multi-character support)
* `Debug`: Enable debug prints

***

#### Shared Config

**File:** `config/shared_config.lua`

**Tobacco Prompts**

```lua
Config.Prompts = {
    Drop = "Drop",
    DropKey = 0x3B24C470,    -- F key
    Smoke = "Smoke",
    Chewing = "Chew",
    SmokeKey = 0x07B8BEAF,   -- Left Mouse Button
    Change = "Change",
    ChangeKey = 0xD51B784F,  -- E key
}
```

Key bindings for tobacco system.

***

#### Item Configuration

**File:** `config/shared_config.lua` (inside `Config.ItemsToUse` table)

**Item Structure**

Each item in `Config.ItemsToUse` follows this format:

```lua
{
    Name = "item_spawn_code",
    Thirst = 0,
    Hunger = 0,
    Metabolism = 0,
    Stamina = 0,
    InnerCoreHealth = 0,
    OuterCoreHealth = 0,
    stress = { mode = "decrease", value = 0 },
    drunk = { mode = "increase", value = 0 },
    Animation = "eat",
    SmokeEvent = "",
    Effect = "",
    EffectDuration = 0,
    PropName = "",
    GiveBackItemLabel = "",
    GiveBackItem = "",
    GiveBackItemAmount = 1,
    InnerCoreHealthGold = 0,
    OuterCoreHealthGold = 0,
    InnerCoreStaminaGold = 0,
    OuterCoreStaminaGold = 0,
    coffeeBuff = {
        enabled = false,
        durationMinutes = 15,
        sleepReduction = 20
    }
}
```

**Field Descriptions**

| Field                  | Type   | Description                                                                                             |
| ---------------------- | ------ | ------------------------------------------------------------------------------------------------------- |
| `Name`                 | String | Item spawn code (must match framework item)                                                             |
| `Thirst`               | Number | Thirst points restored (0-100 scale but can exceed)                                                     |
| `Hunger`               | Number | Hunger points restored (0-100 scale but can exceed)                                                     |
| `Metabolism`           | Number | Metabolism boost                                                                                        |
| `Stamina`              | Number | Stamina points added                                                                                    |
| `InnerCoreHealth`      | Number | Inner health core boost                                                                                 |
| `OuterCoreHealth`      | Number | Outer health core boost                                                                                 |
| `stress`               | Table  | Stress modification: `mode` = `"increase"` or `"decrease"`, `value` = amount                            |
| `drunk`                | Table  | Intoxication modification: `mode` = `"increase"` or `"decrease"`, `value` = amount                      |
| `Animation`            | String | Animation type: `"eat"`, `"drink"`, `"coffee"`, `"stew"`, `"smoke"`, `"chew"`, `"bandage"`, `"syringe"` |
| `SmokeEvent`           | String | For tobacco items, custom prop event                                                                    |
| `Effect`               | String | Visual effect name (e.g., `"PlayerDrunkSaloon1"`)                                                       |
| `EffectDuration`       | Number | Effect duration in minutes                                                                              |
| `PropName`             | String | 3D prop model to display during consumption                                                             |
| `GiveBackItemLabel`    | String | Display name of returned item                                                                           |
| `GiveBackItem`         | String | Item spawn code to return after use (e.g., empty bottle)                                                |
| `GiveBackItemAmount`   | Number | Amount of returned item                                                                                 |
| `InnerCoreHealthGold`  | Number | Duration (minutes) of gold inner health core                                                            |
| `OuterCoreHealthGold`  | Number | Duration (minutes) of gold outer health core                                                            |
| `InnerCoreStaminaGold` | Number | Duration (minutes) of gold inner stamina core                                                           |
| `OuterCoreStaminaGold` | Number | Duration (minutes) of gold outer stamina core                                                           |
| `coffeeBuff`           | Table  | Coffee buff settings (see below)                                                                        |

**Coffee Buff System**

```lua
coffeeBuff = {
    enabled = true,
    durationMinutes = 15,
    sleepReduction = 20
}
```

* `enabled`: Enable coffee buff
* `durationMinutes`: How long buff lasts (reduces sleep accumulation rate)
* `sleepReduction`: Immediately reduce sleep by this amount when consumed

**Example Items**

**Food:**

```lua
{
    Name = "bread",
    Thirst = 50,
    Hunger = 300,
    Metabolism = 150,
    Stamina = 50,
    InnerCoreHealth = 20,
    OuterCoreHealth = 10,
    PropName = "p_bread01x",
    stress = { mode = "decrease", value = 5 },
    drunk = { mode = "decrease", value = 0 },
    Animation = "eat",
    Effect = "",
    EffectDuration = "",
    GiveBackItemLabel = "",
    GiveBackItem = "",
    GiveBackItemAmount = 1
}
```

**Drink:**

```lua
{
    Name = "whisky",
    Thirst = 500,
    Hunger = 0,
    Metabolism = 150,
    Stamina = 50,
    InnerCoreHealth = 50,
    OuterCoreHealth = 25,
    PropName = "s_inv_whiskey02x",
    stress = { mode = "decrease", value = 20 },
    drunk = { mode = "increase", value = 35 },
    Animation = "drink",
    Effect = "PlayerDrunkSaloon1",
    EffectDuration = 1,
    GiveBackItemLabel = "Empty Bottle",
    GiveBackItem = "empty_bottle",
    GiveBackItemAmount = 1
}
```

**Coffee with Buff:**

```lua
{
    Name = "coffee",
    Thirst = 300,
    Hunger = 100,
    Metabolism = 250,
    Stamina = 200,
    InnerCoreHealth = 10,
    OuterCoreHealth = 5,
    InnerCoreHealthGold = 50.0,
    OuterCoreHealthGold = 50.0,
    InnerCoreStaminaGold = 50.0,
    OuterCoreStaminaGold = 50.0,
    PropName = "p_mugcoffee01x",
    stress = { mode = "decrease", value = 10 },
    drunk = { mode = "decrease", value = 5 },
    coffeeBuff = {
        enabled = true,
        durationMinutes = 15,
        sleepReduction = 20
    },
    Animation = "coffee",
    Effect = "",
    EffectDuration = "",
    GiveBackItemLabel = "",
    GiveBackItem = "",
    GiveBackItemAmount = 1
}
```

**Tobacco:**

```lua
{
    Name = "cigarette",
    Thirst = 0,
    Hunger = 0,
    Metabolism = 0,
    Stamina = 2,
    InnerCoreHealth = 0,
    OuterCoreHealth = 0,
    stress = { mode = "decrease", value = 15 },
    drunk = { mode = "increase", value = 0 },
    Animation = "smoke",
    SmokeEvent = "cas-metabolism:prop:cigaret",
    GiveBackItemLabel = "",
    GiveBackItem = "",
    GiveBackItemAmount = 1
}
```

**Medical:**

```lua
{
    Name = "bandage_2",
    Thirst = 0,
    Hunger = 0,
    Metabolism = 0,
    Stamina = 0,
    InnerCoreHealth = 0,
    OuterCoreHealth = 30,
    PropName = "p_cs_bandage01x",
    stress = { mode = "decrease", value = 0 },
    drunk = { mode = "increase", value = 0 },
    Animation = "bandage",
    Effect = "",
    EffectDuration = "",
    GiveBackItemLabel = "",
    GiveBackItem = "",
    GiveBackItemAmount = 1
}
```

***

### Client Exports

All client exports are used from other scripts like this:

```lua
exports['cas-metabolism']:FunctionName(parameters)
```

#### Generic Getters & Setters

**Get Value**

Get any metabolism value by path.

```lua
local value = exports['cas-metabolism']:Get("hunger")
local innerHealth = exports['cas-metabolism']:Get("health.inner")
local outerStamina = exports['cas-metabolism']:Get("stamina.outer")
```

**Parameters:**

* `keyPath` (string): Path to the value (e.g., `"hunger"`, `"health.inner"`)

**Returns:** The value or `nil` if not found

***

**Set Value**

Set any metabolism value by path.

```lua
exports['cas-metabolism']:Set("hunger", 75)
exports['cas-metabolism']:Set("health.inner", 100, { apply = true })
```

**Parameters:**

* `keyPath` (string): Path to the value
* `value` (any): New value to set
* `opts` (table, optional):
  * `apply` (boolean): Apply health/stamina changes to game immediately
  * `flush` (boolean): Force immediate server sync

**Returns:** `true` on success, `false` on failure

***

**Add Value**

Add or subtract from a numeric value.

```lua
exports['cas-metabolism']:Add("hunger", 25)     -- Add 25 hunger
exports['cas-metabolism']:Add("thirst", -10)    -- Remove 10 thirst
```

**Parameters:**

* `keyPath` (string): Path to the numeric value
* `delta` (number): Amount to add (negative to subtract)
* `opts` (table, optional): Same as `Set` options

**Returns:** `true` on success, `false` on failure

***

**Get All Values**

Get all metabolism values at once.

```lua
local all = exports['cas-metabolism']:getAllMetabolismValues()
print(all.hunger)
print(all.thirst)
print(all.health.inner)
```

**Returns:** Table with all current metabolism data

***

#### Specific Getters & Setters

**Hunger**

```lua
-- Get
local hunger = exports['cas-metabolism']:GetHunger()

-- Set
exports['cas-metabolism']:SetHunger(50)

-- Add/Remove
exports['cas-metabolism']:AddHunger(25)
exports['cas-metabolism']:AddHunger(-10)
```

***

**Thirst**

```lua
-- Get
local thirst = exports['cas-metabolism']:GetThirst()

-- Set
exports['cas-metabolism']:SetThirst(75)

-- Add/Remove
exports['cas-metabolism']:AddThirst(30)
exports['cas-metabolism']:AddThirst(-15)
```

***

**Stress**

```lua
-- Get
local stress = exports['cas-metabolism']:GetStress()

-- Set
exports['cas-metabolism']:SetStress(20)

-- Add/Remove
exports['cas-metabolism']:AddStress(10)
exports['cas-metabolism']:AddStress(-5)
```

***

**Drunk**

```lua
-- Get
local drunk = exports['cas-metabolism']:GetDrunk()

-- Set
exports['cas-metabolism']:SetDrunk(35)

-- Add/Remove
exports['cas-metabolism']:AddDrunk(15)
exports['cas-metabolism']:AddDrunk(-10)
```

***

**Sleep**

```lua
-- Get
local sleep = exports['cas-metabolism']:GetSleep()

-- Set
exports['cas-metabolism']:SetSleep(45)

-- Add/Remove
exports['cas-metabolism']:AddSleep(20)
exports['cas-metabolism']:AddSleep(-30)
```

***

**Health (Inner/Outer)**

```lua
-- Get
local innerHealth = exports['cas-metabolism']:GetHealthInner()
local outerHealth = exports['cas-metabolism']:GetHealthOuter()

-- Set (automatically applies to game)
exports['cas-metabolism']:SetHealthInner(80)
exports['cas-metabolism']:SetHealthOuter(100)
```

***

**Stamina (Inner/Outer)**

```lua
-- Get
local innerStamina = exports['cas-metabolism']:GetStaminaInner()
local outerStamina = exports['cas-metabolism']:GetStaminaOuter()

-- Set (automatically applies to game)
exports['cas-metabolism']:SetStaminaInner(90)
exports['cas-metabolism']:SetStaminaOuter(100)
```

***

#### Advanced Functions

**Apply Vitals**

Manually apply health/stamina values from metabolism data to the game.

```lua
exports['cas-metabolism']:ApplyVitalsFromValues()
```

Useful after making multiple changes and wanting to apply them all at once.

***

#### Usage Examples

**Hunger Penalty System:**

```lua
-- In your crafting script
RegisterNetEvent('myserver:craftItem', function()
    local hunger = exports['cas-metabolism']:GetHunger()

    if hunger < 20 then
        -- Not enough energy to craft
        TriggerEvent('chat:addMessage', {
            args = { 'Crafting', 'You are too hungry to craft!' }
        })
        return
    end

    -- Reduce hunger for crafting
    exports['cas-metabolism']:AddHunger(-15)

    -- Continue with crafting...
end)
```

**Reward System:**

```lua
-- Reward player for completing a mission
RegisterNetEvent('mission:complete', function()
    exports['cas-metabolism']:AddHunger(50)
    exports['cas-metabolism']:AddThirst(50)
    exports['cas-metabolism']:AddStress(-25)
end)
```

**Health Check:**

```lua
-- Check if player is healthy enough
local innerHealth = exports['cas-metabolism']:GetHealthInner()
local outerHealth = exports['cas-metabolism']:GetHealthOuter()

if innerHealth < 30 or outerHealth < 30 then
    print("Player needs medical attention!")
end
```

**Force Full Recovery:**

```lua
-- Restore everything (e.g., respawn or teleport to hospital)
exports['cas-metabolism']:SetHunger(100)
exports['cas-metabolism']:SetThirst(100)
exports['cas-metabolism']:SetStress(0)
exports['cas-metabolism']:SetDrunk(0)
exports['cas-metabolism']:SetSleep(0)
exports['cas-metabolism']:SetHealthInner(100)
exports['cas-metabolism']:SetHealthOuter(100)
exports['cas-metabolism']:SetStaminaInner(100)
exports['cas-metabolism']:SetStaminaOuter(100)
```

***

### Server Exports

All server exports are used from other scripts like this:

```lua
exports['cas-metabolism']:FunctionName(parameters)
```

#### Level System Exports

**Get XP**

Get a player's current XP amount.

```lua
local identifier = Framework.GetPlayerIdentifier(Player)
local xp = exports['cas-metabolism']:getXP(identifier)
print("Player XP:", xp)
```

**Parameters:**

* `identifier` (string): Character identifier

**Returns:** XP amount (number)

***

**Add XP**

Give XP to a player.

```lua
local identifier = Framework.GetPlayerIdentifier(Player)
local source = playerId
exports['cas-metabolism']:addXP(50, identifier, source)
```

**Parameters:**

* `amount` (number): XP to add
* `identifier` (string): Character identifier
* `source` (number): Player server ID

**Notes:**

* Automatically handles level-ups (100 XP = 1 level)
* Updates client HUD automatically
* Saves to JSON file

***

**Remove XP**

Remove XP from a player (can cause level down).

```lua
local identifier = Framework.GetPlayerIdentifier(Player)
local source = playerId
exports['cas-metabolism']:removeXP(25, identifier, source)
```

**Parameters:**

* `amount` (number): XP to remove
* `identifier` (string): Character identifier
* `source` (number): Player server ID

**Notes:**

* Can reduce level if XP goes below 0
* Minimum level is 1

***

**Get Level**

Get a player's current level.

```lua
local identifier = Framework.GetPlayerIdentifier(Player)
local level = exports['cas-metabolism']:getLevel(identifier)
print("Player Level:", level)
```

**Parameters:**

* `identifier` (string): Character identifier

**Returns:** Level (number)

***

**Get Level Data**

Get complete level data for a player.

```lua
local identifier = Framework.GetPlayerIdentifier(Player)
local data = exports['cas-metabolism']:getPlayerLevelData(identifier)

if data then
    print("Level:", data.level)
    print("XP:", data.xp)
end
```

**Parameters:**

* `identifier` (string): Character identifier

**Returns:** Table with `{ xp = number, level = number }` or `nil`

***

#### Server Export Usage Examples

**Mission Reward System:**

```lua
RegisterServerEvent('mission:completed')
AddEventHandler('mission:completed', function()
    local src = source
    local Player = Framework.GetPlayer(src)
    local identifier = Framework.GetPlayerIdentifier(Player)

    -- Give 100 XP for completing mission
    exports['cas-metabolism']:addXP(100, identifier, src)

    -- Notify player
    TriggerClientEvent('chat:addMessage', src, {
        args = { 'Mission', 'You earned 100 XP!' }
    })
end)
```

**Level-Based Permissions:**

```lua
RegisterServerEvent('shop:buyItem')
AddEventHandler('shop:buyItem', function(itemName)
    local src = source
    local Player = Framework.GetPlayer(src)
    local identifier = Framework.GetPlayerIdentifier(Player)
    local level = exports['cas-metabolism']:getLevel(identifier)

    if level < 5 then
        TriggerClientEvent('chat:addMessage', src, {
            args = { 'Shop', 'You must be level 5 to buy this item!' }
        })
        return
    end

    -- Continue with purchase...
end)
```

**Death Penalty:**

```lua
RegisterServerEvent('player:died')
AddEventHandler('player:died', function()
    local src = source
    local Player = Framework.GetPlayer(src)
    local identifier = Framework.GetPlayerIdentifier(Player)

    -- Remove 50 XP as death penalty
    exports['cas-metabolism']:removeXP(50, identifier, src)

    TriggerClientEvent('chat:addMessage', src, {
        args = { 'Death', 'You lost 50 XP!' }
    })
end)
```

**Leaderboard System:**

```lua
RegisterCommand('topleaders', function(source, args)
    -- Note: This requires accessing the level system's internal data
    -- You would need to create a custom server function to query all players

    local players = {} -- Get all players from your framework

    for _, player in pairs(players) do
        local identifier = Framework.GetPlayerIdentifier(player)
        local data = exports['cas-metabolism']:getPlayerLevelData(identifier)

        if data then
            table.insert(leaderboard, {
                name = GetPlayerName(player.source),
                level = data.level,
                xp = data.xp
            })
        end
    end

    -- Sort and display...
end)
```

***

### Tips & Best Practices

#### Configuration Tips

1. **Balance Difficulty**: Adjust `ActivityMultipliers` to make survival easier or harder
2. **Grace Periods**: Use `NeedsDecayStartDelay` to give players time after eating/drinking
3. **Stress Management**: Adjust `StressSettings.shootingStressChance` for roleplay vs combat servers
4. **Sleep System**: Modify `gainPerMinute` values to make sleep more/less demanding
5. **Visual Effects**: Disable `EnableShakeEffectForStress` if players find it annoying

#### Export Best Practices

**Client Side:**

* Always check return values when using `Get()` functions
* Use `apply = true` option when changing health/stamina for immediate effect
* Batch multiple changes before applying vitals for better performance

**Server Side:**

* Always validate `identifier` before using level functions
* Store character identifier once instead of calling `GetPlayerIdentifier` repeatedly
* Consider XP balancing: 100 XP per level is default, plan rewards accordingly

#### Common Patterns

**Stat Check Before Action:**

```lua
local hunger = exports['cas-metabolism']:GetHunger()
if hunger < minimumRequired then
    -- Cannot perform action
    return false
end
exports['cas-metabolism']:AddHunger(-cost)
return true
```

**Full Status Reset:**

```lua
function ResetAllStats()
    exports['cas-metabolism']:SetHunger(100)
    exports['cas-metabolism']:SetThirst(100)
    exports['cas-metabolism']:SetSleep(0)
    exports['cas-metabolism']:SetStress(0)
    exports['cas-metabolism']:SetDrunk(0)
    exports['cas-metabolism']:SetHealthInner(100)
    exports['cas-metabolism']:SetHealthOuter(100)
    exports['cas-metabolism']:SetStaminaInner(100)
    exports['cas-metabolism']:SetStaminaOuter(100)
end
```

**Progress Tracking:**

```lua
-- Server side
local identifier = Framework.GetPlayerIdentifier(Player)
local currentXP = exports['cas-metabolism']:getXP(identifier)
local level = exports['cas-metabolism']:getLevel(identifier)
local progress = (currentXP / 100) * 100  -- Percentage to next level

TriggerClientEvent('hud:updateProgress', source, {
    level = level,
    xp = currentXP,
    progress = progress
})
```

***

**For additional support or questions, refer to the script's main files or contact the developer.**


---

# 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://code-after-sex.gitbook.io/script-documentation/about-paid-scripts/redm-script-documentation/metabolism-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.
