# Streaming

### requestModel

Loads a single 3D model with validation and timeout handling.

```lua
B2Lib.Streaming.requestModel(model, timeout, priority)
```

**Parameters:**

* `model` (string|number): Model name or hash to load
* `timeout` (number, optional): Timeout in milliseconds (default: 10000)
* `priority` (boolean, optional): High priority loading (default: false)

**Returns:** boolean - True if model loaded successfully, false otherwise

**Example:**

```lua
local success = B2Lib.Streaming.requestModel("adder", 15000, true)
if success then
    local vehicle = CreateVehicle(GetHashKey("adder"), x, y, z, heading, true, false)
end
```

### releaseModel

Releases a loaded model from memory.

```lua
B2Lib.Streaming.releaseModel(model)
```

**Parameters:**

* `model` (string|number): Model name or hash to release

**Returns:** boolean - True if model was released

### isModelLoaded

Checks if a model is currently loaded in memory.

```lua
B2Lib.Streaming.isModelLoaded(model)
```

**Parameters:**

* `model` (string|number): Model name or hash to check

**Returns:** boolean - True if model is loaded

### requestAnimDict

Loads an animation dictionary with timeout handling.

```lua
B2Lib.Streaming.requestAnimDict(animDict, timeout, priority)
```

**Parameters:**

* `animDict` (string): Animation dictionary name to load
* `timeout` (number, optional): Timeout in milliseconds (default: 10000)
* `priority` (boolean, optional): High priority loading (default: false)

**Returns:** boolean - True if animation dictionary loaded successfully

**Example:**

```lua
local success = B2Lib.Streaming.requestAnimDict("anim@heists@heist_corona@single_team", 15000)
if success then
    TaskPlayAnim(PlayerPedId(), animDict, "single_team_loop_boss", 8.0, 8.0, -1, 1, 0, false, false, false)
end
```

### releaseAnimDict

Releases an animation dictionary from memory.

```lua
B2Lib.Streaming.releaseAnimDict(animDict)
```

**Parameters:**

* `animDict` (string): Animation dictionary name to release

**Returns:** boolean - True if animation dictionary was released

### isAnimDictLoaded

Checks if an animation dictionary is currently loaded.

```lua
B2Lib.Streaming.isAnimDictLoaded(animDict)
```

**Parameters:**

* `animDict` (string): Animation dictionary name to check

**Returns:** boolean - True if animation dictionary is loaded

### requestTextureDict

Loads a texture dictionary with memory optimization.

```lua
B2Lib.Streaming.requestTextureDict(textureDict, timeout, priority)
```

**Parameters:**

* `textureDict` (string): Texture dictionary name to load
* `timeout` (number, optional): Timeout in milliseconds (default: 10000)
* `priority` (boolean, optional): High priority loading (default: false)

**Returns:** boolean - True if texture dictionary loaded successfully

### releaseTextureDict

Releases a texture dictionary from memory.

```lua
B2Lib.Streaming.releaseTextureDict(textureDict)
```

**Parameters:**

* `textureDict` (string): Texture dictionary name to release

**Returns:** boolean - True if texture dictionary was released

### isTextureDictLoaded

Checks if a texture dictionary is currently loaded.

```lua
B2Lib.Streaming.isTextureDictLoaded(textureDict)
```

**Parameters:**

* `textureDict` (string): Texture dictionary name to check

**Returns:** boolean - True if texture dictionary is loaded

### requestModels

Loads multiple models asynchronously with progress tracking.

```lua
B2Lib.Streaming.requestModels(models, callback, timeout, priority)
```

**Parameters:**

* `models` (table): Array of model names or hashes to load
* `callback` (function): Callback function called when complete
* `timeout` (number, optional): Timeout in milliseconds (default: 15000)
* `priority` (boolean, optional): High priority loading (default: false)

**Returns:** string - Request ID for tracking progress

**Example:**

```lua
local models = {"adder", "zentorno", "t20"}
local requestId = B2Lib.Streaming.requestModels(models, function(id, success, timedOut)
    if success then
        print("All models loaded!")
    end
end, 20000)
```

### requestAnimDicts

Loads multiple animation dictionaries asynchronously.

```lua
B2Lib.Streaming.requestAnimDicts(animDicts, callback, timeout, priority)
```

**Parameters:**

* `animDicts` (table): Array of animation dictionary names to load
* `callback` (function): Callback function called when complete
* `timeout` (number, optional): Timeout in milliseconds (default: 15000)
* `priority` (boolean, optional): High priority loading (default: false)

**Returns:** string - Request ID for tracking progress

### requestTextureDicts

Loads multiple texture dictionaries asynchronously.

```lua
B2Lib.Streaming.requestTextureDicts(textureDicts, callback, timeout, priority)
```

**Parameters:**

* `textureDicts` (table): Array of texture dictionary names to load
* `callback` (function): Callback function called when complete
* `timeout` (number, optional): Timeout in milliseconds (default: 15000)
* `priority` (boolean, optional): High priority loading (default: false)

**Returns:** string - Request ID for tracking progress

### getRequestStatus

Gets detailed status information about a streaming request.

```lua
B2Lib.Streaming.getRequestStatus(requestId)
```

**Parameters:**

* `requestId` (string): Request ID to check

**Returns:** table|nil - Request status information or nil if not found

* `id` (string): Request ID
* `type` (string): Request type (models, animdicts, texturedicts)
* `progress` (number): Progress percentage (0.0 to 1.0)
* `loaded` (number): Number of assets loaded
* `total` (number): Total number of assets
* `completed` (boolean): True if request is completed
* `timedOut` (boolean): True if request timed out
* `elapsedTime` (number): Elapsed time in milliseconds
* `averageLoadTime` (number): Average load time per asset
* `priority` (boolean): Request priority level

### getActiveRequests

Gets all currently active streaming requests.

```lua
B2Lib.Streaming.getActiveRequests()
```

**Returns:** table - Array of active request status objects

### cancelRequest

Cancels an active streaming request.

```lua
B2Lib.Streaming.cancelRequest(requestId)
```

**Parameters:**

* `requestId` (string): Request ID to cancel

**Returns:** boolean - True if request was cancelled

### preloadArea

Preloads assets for a specific area with radius-based loading.

```lua
B2Lib.Streaming.preloadArea(coords, radius, callback, priority)
```

**Parameters:**

* `coords` (vector3): Center coordinates for preloading
* `radius` (number): Preload radius in units
* `callback` (function, optional): Callback when preloading completes
* `priority` (boolean, optional): High priority loading (default: false)

**Returns:** string - Request ID for tracking progress

**Example:**

```lua
local requestId = B2Lib.Streaming.preloadArea(vector3(100, 200, 30), 200.0, function(id, success)
    if success then
        print("Area preloaded successfully")
    end
end)
```

### releaseAll

Releases all loaded assets or specific asset types from memory.

```lua
B2Lib.Streaming.releaseAll(assetType, excludePriority)
```

**Parameters:**

* `assetType` (string, optional): Asset type to release ("models", "animdicts", "texturedicts")
* `excludePriority` (boolean, optional): Exclude priority assets (default: true)

**Returns:** number - Number of assets released

**Example:**

```lua
B2Lib.Streaming.releaseAll()                    -- Release all assets
B2Lib.Streaming.releaseAll("models")            -- Only models
B2Lib.Streaming.releaseAll(nil, false)          -- Include priority assets
```

### cleanupOld

Cleans up assets that haven't been used for a specified time.

```lua
B2Lib.Streaming.cleanupOld(maxAge, excludePriority)
```

**Parameters:**

* `maxAge` (number, optional): Maximum age in milliseconds (default: 300000)
* `excludePriority` (boolean, optional): Exclude priority assets (default: true)

**Returns:** number - Number of assets cleaned up

### isInStreamingRange

Checks if an asset should be loaded based on distance from coordinates.

```lua
B2Lib.Streaming.isInStreamingRange(asset, coords, customRange)
```

**Parameters:**

* `asset` (string): Asset name to check
* `coords` (vector3, optional): Coordinates to check from (default: player position)
* `customRange` (number, optional): Custom streaming range override

**Returns:** boolean - True if asset should be loaded

### getStatus

Gets comprehensive streaming system status and statistics.

```lua
B2Lib.Streaming.getStatus()
```

**Returns:** table - Streaming system status

* `loadedModels` (number): Number of loaded models
* `loadedAnimDicts` (number): Number of loaded animation dictionaries
* `loadedTextureDicts` (number): Number of loaded texture dictionaries
* `totalAssets` (number): Total loaded assets
* `memoryUsage` (number): Estimated memory usage in MB
* `activeRequests` (number): Number of active requests
* `completedRequests` (number): Number of completed requests
* `failedRequests` (number): Number of failed requests
* `averageLoadTime` (number): Average load time per asset
* `cacheHitRate` (number): Cache hit rate percentage

### updateConfig

Updates streaming system configuration.

```lua
B2Lib.Streaming.updateConfig(newConfig)
```

**Parameters:**

* `newConfig` (table): Configuration options to update

**Returns:** void

### Configuration

Configure the streaming system in `config.lua`:

```lua
Config.Streaming = {
    defaultTimeout = 10000,         -- Default timeout in milliseconds
    maxConcurrentRequests = 5,      -- Maximum concurrent requests
    enableMemoryTracking = true,    -- Enable memory usage tracking
    enableCaching = true,           -- Enable asset caching
    maxCacheSize = 1000,           -- Maximum cached assets
    cleanupInterval = 300000,       -- Cleanup interval in milliseconds
    streamingRange = 500.0,         -- Default streaming range
    priorityMultiplier = 2.0,       -- Priority request multiplier
    enableDebugMode = false,        -- Enable debug logging
    memoryWarningThreshold = 512,   -- Memory warning threshold in MB
    autoCleanupEnabled = true,      -- Enable automatic cleanup
    batchSize = 10                  -- Batch processing size
}
```

### Troubleshooting

#### Assets Not Loading

1. Check that asset names are correct and exist
2. Verify timeout values are sufficient for asset size
3. Ensure memory limits aren't exceeded
4. Check for conflicting resource requests

#### Performance Issues

1. Reduce concurrent request limits
2. Use batch loading instead of individual requests
3. Enable asset caching for frequently used assets
4. Implement proper cleanup strategies

#### Memory Problems

1. Monitor memory usage with `getStatus()`
2. Use `cleanupOld()` to remove unused assets
3. Release assets when no longer needed
4. Reduce cache size if memory is limited

#### Request Timeouts

1. Increase timeout values for large assets
2. Check network connectivity and server performance
3. Reduce concurrent requests to avoid bottlenecks
4. Use priority loading for critical assets

#### Streaming Range Issues

1. Verify coordinates are valid and within world bounds
2. Adjust streaming range based on gameplay requirements
3. Use custom ranges for specific scenarios
4. Check if assets are being loaded too early or late
