Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Untitled conversation

  1. User
    local Vector3D = require("vector3d")
    local SphereLibrary = {}
    local spheres = {}
    local nextSphereId = 1
    local mathRad = math.rad
    local TWO_PI, PI = mathRad(360), mathRad(180)
    local MAX_DETAIL_LEVEL = 20
    local DEFAULT_DETAIL_LEVEL = 5
    local DEFAULT_COLOR = 0xFFFFFF
    local MAX_RENDER_DISTANCE = 1000
    local debugMode = false
    local function clamp(value, min, max)
        if value < min then return min end
        if value > max then return max end
        return value
    end
    
    local function isValidPed(ped)
        return ped ~= nil and isCharacter(ped)
    end
    
    local function calculateDistance(pos1, pos2)
        local dx = pos1.x - pos2.x
        local dy = pos1.y - pos2.y
        local dz = pos1.z - pos2.z
        return math.sqrt(dx * dx + dy * dy + dz * dz)
    end
    
    local function safeGetCharCoordinates(pPed)
        local success, coords = pcall(getCharCoordinates, pPed)
        if success and type(coords) == "table" and coords.x and coords.y and coords.z then
            return coords
        else
            if debugMode then print("Error: Failed to get character coordinates for pPed:", pPed) end
            return {
                x = 0,
                y = 0,
                z = 0
            }
        end
    end
    
    local function isWithinRenderDistance(sphereCenter, cameraPos)
        local distance = calculateDistance(sphereCenter, cameraPos)
        return distance <= MAX_RENDER_DISTANCE
    end
    
    local function addVectors(v1, v2)
        return Vector3D(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z)
    end
    
    local function updatePosition(sphere)
        if sphere.followPlayer then
            if sphere.pPed and isValidPed(sphere.pPed) then
                local coords = safeGetCharCoordinates(sphere.pPed)
                sphere.center = Vector3D(coords.x, coords.y, coords.z)
            else
                if debugMode then print("Warning: Invalid pPed in sphere ID:", sphere.id) end
            end
        end
    end
    
    local function calculatePoint(sphere, phi, theta)
        local sinPhi = math.sin(phi)
        local x = sphere.radius * sinPhi * math.cos(theta)
        local y = sphere.radius * sinPhi * math.sin(theta)
        local z = sphere.radius * math.cos(phi)
        return addVectors(Vector3D(x, y, z), sphere.center)
    end
    
    local function renderLine(point1, point2, width, color, sphereId)
        local visible1, screenX1, screenY1 = convert3DCoordsToScreenEx(point1.x, point1.y, point1.z)
        local visible2, screenX2, screenY2 = convert3DCoordsToScreenEx(point2.x, point2.y, point2.z)
        if visible1 and visible2 then
            renderDrawLine(screenX1, screenY1, screenX2, screenY2, width, color)
        else
            if debugMode then print(string.format("Line not rendered: Point1 visible=%s, Point2 visible=%s for sphere ID: %s", tostring(visible1), tostring(visible2), sphereId)) end
        end
    end
    
    local function renderSphere(sphere)
        local stepTheta = TWO_PI / sphere.detailLevel
        local stepPhi = PI / sphere.detailLevel
        local numThetaSteps = sphere.detailLevel
        local numPhiSteps = sphere.detailLevel
        for i = 0, numThetaSteps do
            local theta = i * stepTheta
            for j = 1, numPhiSteps - 1 do
                local phi = j * stepPhi
                local point1 = calculatePoint(sphere, phi, theta)
                local point2 = calculatePoint(sphere, phi, theta + stepTheta)
                local point3 = calculatePoint(sphere, phi + stepPhi, theta)
                renderLine(point1, point2, 1, sphere.color, sphere.id)
                renderLine(point1, point3, 1, sphere.color, sphere.id)
            end
        end
    end
    
    local function isPointInSphere(point, center, radius)
        if type(point.x) ~= "number" or type(center.x) ~= "number" or type(point.y) ~= "number" or type(center.y) ~= "number" or type(point.z) ~= "number" or type(center.z) ~= "number" then
            if debugMode then print("Error: Non-numeric coordinates provided to isPointInSphere.") end
            return false
        end
    
        local dx, dy, dz = point.x - center.x, point.y - center.y, point.z - center.z
        return (dx * dx + dy * dy + dz * dz) <= (radius * radius)
    end
    
    function SphereLibrary.collectEntitiesInSphere(sphereId)
        local sphere = spheres[sphereId]
        if not sphere then
            print(string.format("Warning: Invalid sphereId '%s' provided to collectEntitiesInSphere.", sphereId))
            return {
                objects = {},
                players = {},
                cars = {}
            }
        end
    
        local entitiesInside = {
            objects = {},
            players = {},
            cars = {}
        }
    
        local function addEntities(getAllEntities, getCoords, getId, entityKey)
            local allEntities = getAllEntities()
            if type(allEntities) ~= "table" then
                print(string.format("Error: %s did not return a table.", tostring(getAllEntities)))
                return
            end
    
            for _, entity in ipairs(allEntities) do
                local coords = getCoords(entity)
                if not coords then
                    if debugMode then print(string.format("Warning: Failed to get coordinates for entity in '%s'.", entityKey)) end
                else
                    local entityPoint = Vector3D(coords.x, coords.y, coords.z)
                    if isPointInSphere(entityPoint, sphere.center, sphere.radius) then
                        local success, entityId = pcall(getId, entity)
                        if success and entityId then
                            table.insert(entitiesInside[entityKey], entityId)
                        elseif debugMode then
                            print(string.format("Error: Failed to get ID for entity in '%s'.", entityKey))
                        end
                    end
                end
            end
        end
    
        addEntities(getAllObjects, getObjectCoordinates, sampGetObjectSampIdByHandle, "objects")
        addEntities(getAllChars, getCharCoordinates, sampGetPlayerIdByCharHandle, "players")
        addEntities(getAllVehicles, getCarCoordinates, sampGetVehicleIdByCarHandle, "cars")
        if next(entitiesInside.objects) == nil and next(entitiesInside.players) == nil and next(entitiesInside.cars) == nil and debugMode then print(string.format("Info: No entities found within sphere ID: %s.", sphereId)) end
        return entitiesInside
    end
    
    function SphereLibrary.createSphere(playerPed, radius, followPlayer, centerX, centerY, centerZ, detailLevel, color)
        if type(radius) ~= "number" or radius <= 0 then error("Invalid radius provided to createSphere. Must be a positive number.") end
        if followPlayer and not isValidPed(playerPed) then error("Invalid playerPed provided to createSphere.") end
        centerX = (type(centerX) == "number") and centerX or 0
        centerY = (type(centerY) == "number") and centerY or 0
        centerZ = (type(centerZ) == "number") and centerZ or 0
        detailLevel = (type(detailLevel) == "number" and detailLevel > 0) and clamp(math.floor(detailLevel), 1, MAX_DETAIL_LEVEL) or DEFAULT_DETAIL_LEVEL
        color = (type(color) == "number") and color or DEFAULT_COLOR
        local sphereId = nextSphereId
        nextSphereId = nextSphereId + 1
        spheres[sphereId] = {
            id = sphereId,
            pPed = playerPed,
            radius = radius,
            followPlayer = followPlayer,
            center = Vector3D(centerX, centerY, centerZ),
            detailLevel = detailLevel,
            color = color
        }
    
        if debugMode then print(string.format("Sphere created with ID: %s", sphereId)) end
        return sphereId
    end
    
    function SphereLibrary.removeSphere(sphereId)
        if spheres[sphereId] then
            spheres[sphereId] = nil
            if debugMode then print(string.format("Sphere with ID: %s removed.", sphereId)) end
        else
            print(string.format("Warning: Attempted to remove a non-existent sphereId '%s'.", sphereId))
        end
    end
    
    function SphereLibrary.updateRender()
        local cameraCoords = getCameraCoordinates()
        for _, currentSphere in pairs(spheres) do
            updatePosition(currentSphere)
            if cameraCoords then
                if isWithinRenderDistance(currentSphere.center, cameraCoords) and isPointOnScreen(currentSphere.center.x, currentSphere.center.y, currentSphere.center.z) then renderSphere(currentSphere) end
            else
                if isPointOnScreen(currentSphere.center.x, currentSphere.center.y, currentSphere.center.z) then renderSphere(currentSphere) end
            end
        end
    end
    
    function SphereLibrary.setDebugMode(enabled)
        debugMode = enabled and true or false
        print(string.format("Debug mode %s.", debugMode and "enabled" or "disabled"))
    end
    return SphereLibrary
    

    Напиши readme.txt файл который содержит информацию о том как правильно применить библиотеку, документацию по этой библиотеке подробную.

  2. Assistant
    ======================================================================
                             SPHERELIBRARY README
    ======================================================================
    
    **Version:** 1.0  
    **Author:** [Your Name]  
    **Last Updated:** October 2023  
    
    ---
    
    ## Table of Contents
    
    1. [Introduction](#introduction)
    2. [Features](#features)
    3. [Requirements](#requirements)
    4. [Installation](#installation)
    5. [Usage](#usage)
        - [Creating a Sphere](#creating-a-sphere)
        - [Removing a Sphere](#removing-a-sphere)
        - [Updating Render](#updating-render)
        - [Collecting Entities in a Sphere](#collecting-entities-in-a-sphere)
        - [Setting Debug Mode](#setting-debug-mode)
    6. [API Reference](#api-reference)
    7. [Examples](#examples)
    8. [Troubleshooting](#troubleshooting)
    9. [License](#license)
    10. [Contact](#contact)
    
    ---
    
    ## Introduction
    
    **SphereLibrary** is a Lua module designed for managing, rendering, and interacting with 3D spheres within a game or simulation environment. It provides functionalities to create dynamic spheres that can follow players, render them on the screen, and collect entities (such as objects, players, and vehicles) that reside within these spheres.
    
    ---
    
    ## Features
    
    - **Dynamic Sphere Creation:** Create spheres with customizable radius, color, and detail level.
    - **Follow Player:** Option to attach spheres to player characters, making them follow in real-time.
    - **Rendering:** Efficiently render spheres on the screen with adjustable detail levels.
    - **Entity Collection:** Collect and categorize entities (objects, players, cars) residing within a sphere.
    - **Debug Mode:** Enable detailed debugging information to assist in development and troubleshooting.
    - **Performance Optimizations:** Includes clamping, distance calculations, and conditional rendering based on camera position to optimize performance.
    
    ---
    
    ## Requirements
    
    Before using SphereLibrary, ensure the following dependencies and environment setups are met:
    
    - **Lua 5.x:** Compatible with Lua 5.x versions.
    - **Vector3D Module:** Requires the `vector3d` module for 3D vector operations.
    - **Game/Simulation Environment Functions:** Ensure the following functions are available in your environment:
        - `isCharacter(ped)`
        - `getCharCoordinates(pPed)`
        - `convert3DCoordsToScreenEx(x, y, z)`
        - `renderDrawLine(x1, y1, x2, y2, width, color)`
        - `getCameraCoordinates()`
        - `isPointOnScreen(x, y, z)`
        - `getAllObjects()`
        - `getObjectCoordinates(object)`
        - `sampGetObjectSampIdByHandle(handle)`
        - `getAllChars()`
        - `getPlayerIdByCharHandle(handle)`
        - `getAllVehicles()`
        - `getCarCoordinates(vehicle)`
        - `sampGetVehicleIdByCarHandle(handle)`
    
    *Note:* These functions are typically provided by the game or simulation environment (e.g., GTA modding APIs).
    
    ---
    
    ## Installation
    
    1. **Download SphereLibrary:**
       - Save the provided `SphereLibrary.lua` file to your project’s library or modules directory.
    
    2. **Ensure Dependencies:**
       - Make sure the `vector3d` module is available and properly required in your project.
       - Verify that all required environment functions are accessible.
    
    3. **Require the Library:**
       ```lua
       local SphereLibrary = require("SphereLibrary")
    

    Usage

    Creating a Sphere

    To create a new sphere:

    local sphereId = SphereLibrary.createSphere(
        playerPed,           -- playerPed: The player character to follow (nil if not following)
        50,                  -- radius: Radius of the sphere
        true,                -- followPlayer: Boolean indicating if the sphere should follow the player
        100,                 -- centerX: X-coordinate of the sphere center (used if not following)
        200,                 -- centerY: Y-coordinate of the sphere center
        300,                 -- centerZ: Z-coordinate of the sphere center
        10,                  -- detailLevel: Detail level (number of subdivisions)
        0xFF0000             -- color: Color of the sphere in hexadecimal (e.g., 0xFF0000 for red)
    )
    

    Parameters:

    • playerPed (optional): The player character to attach the sphere to. Use nil if not attaching.
    • radius (number): The radius of the sphere. Must be a positive number.
    • followPlayer (boolean): If true, the sphere will follow the specified player character.
    • centerX, centerY, centerZ (numbers): Coordinates for the sphere’s center if not following a player.
    • detailLevel (number, optional): Determines the smoothness of the sphere. Defaults to 5. Max 20.
    • color (number, optional): The color of the sphere in hexadecimal. Defaults to 0xFFFFFF (white).

    Returns:

    • sphereId (number): A unique identifier for the created sphere.

    Removing a Sphere

    To remove an existing sphere:

    SphereLibrary.removeSphere(sphereId)
    

    Parameters:

    • sphereId (number): The unique identifier of the sphere to remove.

    Updating Render

    To update the rendering of all spheres (typically called every frame or tick):

    SphereLibrary.updateRender()
    

    Usage:

    Call this function in your main update loop to ensure all spheres are rendered correctly based on their current state and position.

    Collecting Entities in a Sphere

    To collect entities that reside within a specific sphere:

    local entities = SphereLibrary.collectEntitiesInSphere(sphereId)
    
    -- Access collected entities
    local objects = entities.objects      -- Table of object IDs
    local players = entities.players      -- Table of player IDs
    local cars = entities.cars            -- Table of car IDs
    

    Parameters:

    • sphereId (number): The unique identifier of the sphere to query.

    Returns:

    • entities (table): Contains three tables:
      • objects: List of object IDs within the sphere.
      • players: List of player IDs within the sphere.
      • cars: List of car IDs within the sphere.

    Setting Debug Mode

    To enable or disable debug mode:

    SphereLibrary.setDebugMode(true)   -- Enable debug mode
    SphereLibrary.setDebugMode(false)  -- Disable debug mode
    

    Parameters:

    • enabled (boolean): Pass true to enable debug mode or false to disable it.

    Effect:

    When enabled, the library will print detailed debugging information to the console, assisting in development and troubleshooting.


    API Reference

    SphereLibrary.createSphere(playerPed, radius, followPlayer, centerX, centerY, centerZ, detailLevel, color)

    Creates a new sphere with the specified parameters.

    • Parameters:
      • playerPed (optional): Player character to follow (nil if not).
      • radius (number): Radius of the sphere (> 0).
      • followPlayer (boolean): Whether the sphere follows the player.
      • centerX, centerY, centerZ (numbers): Center coordinates if not following.
      • detailLevel (number, optional): Detail level (1 to 20). Defaults to 5.
      • color (number, optional): Hex color value. Defaults to 0xFFFFFF.
    • Returns:
      • sphereId (number): Unique identifier for the sphere.

    SphereLibrary.removeSphere(sphereId)

    Removes a sphere based on its ID.

    • Parameters:
      • sphereId (number): The ID of the sphere to remove.

    SphereLibrary.updateRender()

    Updates and renders all active spheres. Should be called regularly, such as within a game loop.

    SphereLibrary.collectEntitiesInSphere(sphereId)

    Collects entities within the specified sphere.

    • Parameters:
      • sphereId (number): The ID of the sphere to query.
    • Returns:
      • entities (table): Contains objects, players, and cars tables with respective IDs.

    SphereLibrary.setDebugMode(enabled)

    Enables or disables debug mode.

    • Parameters:
      • enabled (boolean): true to enable, false to disable.

    Examples

    Example 1: Creating and Rendering a Sphere Attached to a Player

    local SphereLibrary = require("SphereLibrary")
    
    -- Assume 'playerPed' is your player character handle
    local playerPed = getPlayerPed()  -- Replace with actual function to get playerPed
    
    -- Create a sphere that follows the player
    local sphereId = SphereLibrary.createSphere(
        playerPed,       -- Attach to player
        100,             -- Radius of 100 units
        true,            -- Follow the player
        0, 0, 0,         -- Center coordinates (ignored if following)
        10,              -- Detail level
        0x00FF00         -- Green color
    )
    
    -- In your main update loop
    function onUpdate()
        -- Update rendering
        SphereLibrary.updateRender()
    
        -- Example: Collect entities within the sphere
        local entities = SphereLibrary.collectEntitiesInSphere(sphereId)
        print("Objects in sphere:", #entities.objects)
        print("Players in sphere:", #entities.players)
        print("Cars in sphere:", #entities.cars)
    end
    

    Example 2: Creating a Static Sphere

    local SphereLibrary = require("SphereLibrary")
    
    -- Create a static sphere at coordinates (500, 500, 20)
    local sphereId = SphereLibrary.createSphere(
        nil,             -- Not following any player
        150,             -- Radius of 150 units
        false,           -- Do not follow
        500, 500, 20,    -- Center coordinates
        15,              -- Detail level
        0x0000FF         -- Blue color
    )
    
    -- In your main update loop
    function onUpdate()
        -- Update rendering
        SphereLibrary.updateRender()
    
        -- Example: Check entities
        local entities = SphereLibrary.collectEntitiesInSphere(sphereId)
        -- Process entities as needed
    end
    

    Example 3: Enabling Debug Mode

    local SphereLibrary = require("SphereLibrary")
    
    -- Enable debug mode
    SphereLibrary.setDebugMode(true)
    
    -- Create a sphere
    local sphereId = SphereLibrary.createSphere(nil, 100, false, 250, 250, 30, 10, 0xFFFF00)
    
    -- Remove a sphere
    SphereLibrary.removeSphere(sphereId)
    

    Troubleshooting

    • Sphere Not Rendering:

      • Ensure updateRender is being called regularly.
      • Verify that the sphere is within the MAX_RENDER_DISTANCE.
      • Check if the sphere's center coordinates are correct.
    • Entities Not Being Collected:

      • Ensure the entity collection functions (getAllObjects, getAllChars, getAllVehicles, etc.) are returning valid tables.
      • Verify that isPointInSphere is receiving proper numeric coordinates.
    • Errors Related to Dependencies:

      • Confirm that the vector3d module is correctly installed and required.
      • Ensure all required environment functions are accessible and correctly implemented.
    • Debug Mode Insights:

      • Enable debug mode to receive detailed logs that can help identify issues.
      • Look for warning and error messages in the console to guide troubleshooting.

    License

    [Specify your license here, e.g., MIT License]


    Contact

    For questions, suggestions, or support, please contact:


    ====================================================================== THANK YOU FOR USING SPHERELIBRARY