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

Untitled conversation

  1. User
    if CLIENT then
        -- Функция для создания уведомления
        local function CreateNotification(text, modelPath)
            -- Создаем панель уведомления
            local frame = vgui.Create("DPanel")
            frame:SetSize(300, 100) -- Размер окна
            frame:SetPos(ScrW(), ScrH() / 2 - 50) -- Начальная позиция за экраном справа
            frame:ParentToHUD() -- Привязка к HUD
    
            -- Установка кастомного фона
            function frame:Paint(w, h)
                draw.RoundedBox(8, 0, 0, w, h, Color(50, 50, 50, 200)) -- Серый полупрозрачный фон
            end
    
            -- Добавление текста
            local lbl = vgui.Create("DLabel", frame)
            lbl:SetPos(100, 10)
            lbl:SetSize(180, 80)
            lbl:SetText(text)
            lbl:SetTextColor(Color(255, 255, 255))
            lbl:SetWrap(true)
            lbl:SetContentAlignment(5) -- Центрирование текста
    
            -- Добавление модели
            local mdl = vgui.Create("DModelPanel", frame)
            mdl:SetPos(10, 10)
            mdl:SetSize(80, 80)
            mdl:SetModel(modelPath or "models/player/kleiner.mdl") -- Модель по умолчанию
    
            -- Установка позиции камеры модели
            local min, max = mdl.Entity:GetRenderBounds()
            local size = 0
            size = math.max(max.x - min.x, max.y - min.y, max.z - min.z)
            mdl:SetFOV(45)
            mdl:SetCamPos(Vector(size, size, size))
            mdl:SetLookAt((min + max) * 0.5)
    
            -- Анимация вращения модели
            function mdl:LayoutEntity(entity)
                entity:SetAngles(Angle(0, CurTime() * 30, 0))
            end
    
            -- Анимация появления окна
            frame:MoveTo(ScrW() - 310, ScrH() / 2 - 50, 0.5, 0, -1, function()
                -- После появления ждем 5 секунд и скрываем
                timer.Simple(5, function()
                    if IsValid(frame) then
                        frame:MoveTo(ScrW(), ScrH() / 2 - 50, 0.5, 0, -1, function()
                            if IsValid(frame) then
                                frame:Remove()
                            end
                        end)
                    end
                end)
            end)
        end
    
        -- Получение уведомления от сервера
        net.Receive("ShowNotification", function()
            local text = net.ReadString()
            local model = net.ReadString()
            CreateNotification(text, model)
        end)
    
        -- Опционально: локальная команда для тестирования уведомления на клиенте
        concommand.Add("show_notification_client", function()
            CreateNotification("Это тестовое уведомление.", "models/player/alyx.mdl")
        end)
    end
    
    -- Регистрация сетевого сообщения
    if SERVER then
        util.AddNetworkString("ShowNotification")
    
        -- Функция отправки уведомления конкретному игроку
        local function SendNotification(ply, text, modelPath)
            net.Start("ShowNotification")
                net.WriteString(text)
                net.WriteString(modelPath)
            net.Send(ply)
        end
    
        -- Функция проверки формата Steam ID
        local function IsValidSteamID(sid)
            -- Проверка формата STEAM_X:Y:Z, где X, Y, Z - цифры
            return string.match(sid, "^STEAM_%d:%d:%d+$") ~= nil
        end
    
        -- Консольная команда для отправки уведомлений
        -- Использование: show_notification_server <steam_id> <текст> [<путь_к_модели>]
        concommand.Add("show_notification_server", function(ply, cmd, args)
            -- Проверка прав: только администраторы могут использовать команду
            if IsValid(ply) and not ply:IsAdmin() then
                ply:ChatPrint("У вас нет прав для использования этой команды.")
                return
            end
    
            -- Проверка количества аргументов
            if #args < 2 then
                if IsValid(ply) then
                    ply:ChatPrint("Использование: show_notification_server <steam_id> <текст> [<путь_к_модели>]")
                else
                    print("Использование: show_notification_server <steam_id> <текст> [<путь_к_модели>]")
                end
                return
            end
    
            local steamID = args[1]
            -- Используем собственную функцию для проверки Steam ID
            if not IsValidSteamID(steamID) then
                if IsValid(ply) then
                    ply:ChatPrint("Неверный формат Steam ID. Пример: STEAM_0:1:123456")
                else
                    print("Неверный формат Steam ID. Пример: STEAM_0:1:123456")
                end
                return
            end
    
            table.remove(args, 1) -- Удаляем Steam ID из аргументов
    
            -- Определяем, есть ли модель в качестве последнего аргумента
            local model = "models/player/alyx.mdl" -- Модель по умолчанию
            if string.find(args[#args], "^models/") then
                model = args[#args]
                table.remove(args, #args) -- Удаляем модель из аргументов
            end
    
            local text = table.concat(args, " ")
    
            -- Поиск игрока по Steam ID
            local target = player.GetBySteamID(steamID)
    
            if target and IsValid(target) then
                SendNotification(target, text, model)
                if IsValid(ply) then
                    ply:ChatPrint("Уведомление отправлено игроку " .. target:Nick())
                else
                    print("Уведомление отправлено игроку " .. target:Nick())
                end
            else
                if IsValid(ply) then
                    ply:ChatPrint("Игрок с Steam ID \"" .. steamID .. "\" не найден или не онлайн.")
                else
                    print("Игрок с Steam ID \"" .. steamID .. "\" не найден или не онлайн.")
                end
            end
        end)
    end
    

    Займись аудитом кода и код-ревью, затем проведки рефакторинг и профилирование кода.

  2. Assistant

    Code Audit and Code Review

    1. Overview

    You've provided two Lua scripts intended for a Garry's Mod (GMod) environment:

    • Client-Side Script:

      • Handles the creation and display of notifications using VGUI.
      • Listens for network messages (ShowNotification) to trigger notifications.
      • Includes a console command for testing notifications locally.
    • Server-Side Script:

      • Registers the network message (ShowNotification).
      • Defines a function to send notifications to specific players.
      • Includes input validation for Steam IDs.
      • Provides a console command for administrators to send notifications to players.

    2. Audit Findings

    a. Security Considerations

    • Authorization: The server-side show_notification_server command correctly restricts usage to administrators. However, ensure that any method of setting a player as an admin is secure to prevent unauthorized access.

    • Input Validation:

      • Steam ID Validation: The IsValidSteamID function checks for the format STEAM_X:Y:Z. While this ensures correct formatting, it doesn't verify the existence of the Steam ID in the server's player list. However, later in the code, you attempt to find the player by Steam ID, which is appropriate.
      • Model Path Validation: The script assumes that any string starting with models/ is a valid model path. An attacker could potentially provide a malicious or incorrect model path. Consider validating model paths against a whitelist or ensuring the model exists before applying it.
    • Net Message Handling: Ensure that only legitimate server messages (ShowNotification) are sent. Since the client only listens for this specific message, and it's sent from the server after validation, this is acceptable.

    b. Performance Considerations

    • VGUI Panel Creation:

      • Creating VGUI elements every time a notification is shown can be resource-intensive if used excessively. Consider reusing panels or implementing pooling if notifications are frequent.
    • Model Rendering:

      • Continuously rendering models with animations can impact client performance, especially if multiple notifications appear simultaneously. Benchmark performance when multiple notifications are active.
    • Timers:

      • The use of timer.Simple is acceptable, but if there are many notifications, ensure that timers are managed efficiently to prevent potential memory leaks.

    c. Code Quality and Maintainability

    • Hardcoded Values:

      • Positions, sizes, and default values are hardcoded (e.g., frame size 300x100, default model models/player/alyx.mdl). Consider using configurable variables or constants for easier adjustments.
    • Localization:

      • Text strings are in Russian. If the addon is intended for an international audience, consider implementing localization support.
    • Error Handling:

      • While there are checks for argument counts and Steam ID format, additional error handling could be implemented. For instance, handling cases where the model fails to load.
    • Code Duplication:

      • Some messages are sent both to the server console (if executed server-side) and to the player's chat. Ensure consistency in how messages are relayed.
    • Naming Conventions:

      • Function and variable names are clear and descriptive, which is good for readability.

    3. Refactoring Suggestions

    Based on the audit, here are some refactoring suggestions to improve security, performance, and maintainability.

    a. Client-Side Script Refactoring

    1. Use Constants for Configurable Values: Define constants at the top for sizes, positions, colors, and default models.

    2. Model Path Validation: Implement a function to verify if the model exists before setting it in the DModelPanel.

    3. Reusing VGUI Panels: Implement a pooling mechanism or reuse panels to reduce the overhead of creating and destroying panels frequently.

    4. Localization Support: Use a table or library to handle text strings for easier localization.

    5. Error Handling: Add error handling for missing or invalid model paths.

    6. Optimizing Render Bounds Calculation: Cache or optimize the calculation of render bounds to improve performance.

    b. Server-Side Script Refactoring

    1. Whitelist Valid Model Paths: Define a whitelist of acceptable model paths to prevent misuse.

    2. Enhance Steam ID Validation: Beyond format checking, verify if the Steam ID corresponds to a currently online player.

    3. Extract Logging and Messaging: Create helper functions for sending chat prints and console messages to reduce code duplication.

    4. Simplify Argument Parsing: Modularize the argument parsing for better readability and maintenance.

    5. Use Net Library Functions Appropriately: Consider using net.Broadcast or other net functions if broader notification mechanisms are needed in the future.

    4. Refactored Code

    Below is the refactored version of both client and server scripts incorporating the above suggestions.


    Client-Side Refactored Script (cl_init.lua)

    if CLIENT then
        -- Constants
        local NOTIFICATION_WIDTH, NOTIFICATION_HEIGHT = 300, 100
        local NOTIFICATION_X_START = ScrW()
        local NOTIFICATION_Y = ScrH() / 2 - (NOTIFICATION_HEIGHT / 2)
        local NOTIFICATION_BG_COLOR = Color(50, 50, 50, 200)
        local TEXT_COLOR = Color(255, 255, 255)
        local DEFAULT_MODEL = "models/player/kleiner.mdl"
        local ANIMATION_DURATION = 0.5 -- seconds
        local DISPLAY_DURATION = 5 -- seconds
    
        -- Helper function to validate model path
        local function IsValidModel(modelPath)
            return util.IsValidModel(modelPath)
        end
    
        -- Function to create and display a notification
        local function CreateNotification(text, modelPath)
            modelPath = modelPath and (IsValidModel(modelPath) and modelPath or DEFAULT_MODEL) or DEFAULT_MODEL
    
            -- Create the notification panel
            local frame = vgui.Create("DPanel")
            frame:SetSize(NOTIFICATION_WIDTH, NOTIFICATION_HEIGHT)
            frame:SetPos(NOTIFICATION_X_START, NOTIFICATION_Y)
            frame:ParentToHUD()
    
            -- Set custom background
            function frame:Paint(w, h)
                draw.RoundedBox(8, 0, 0, w, h, NOTIFICATION_BG_COLOR)
            end
    
            -- Add text label
            local lbl = vgui.Create("DLabel", frame)
            lbl:SetPos(100, 10)
            lbl:SetSize(180, 80)
            lbl:SetText(text)
            lbl:SetTextColor(TEXT_COLOR)
            lbl:SetWrap(true)
            lbl:SetContentAlignment(5) -- Center
    
            -- Add model panel
            local mdl = vgui.Create("DModelPanel", frame)
            mdl:SetPos(10, 10)
            mdl:SetSize(80, 80)
            mdl:SetModel(modelPath)
    
            -- Ensure model is valid
            if not IsValid(mdl.Entity) or mdl.Entity:GetModel() ~= modelPath then
                mdl:SetModel(DEFAULT_MODEL)
            end
    
            -- Set camera for model
            local min, max = mdl.Entity:GetRenderBounds()
            local size = math.max(max.x - min.x, max.y - min.y, max.z - min.z)
            mdl:SetFOV(45)
            mdl:SetCamPos(Vector(size, size, size))
            mdl:SetLookAt((min + max) * 0.5)
    
            -- Rotate model
            function mdl:LayoutEntity(entity)
                entity:SetAngles(Angle(0, CurTime() * 30, 0))
            end
    
            -- Animate the notification sliding in
            frame:MoveTo(ScrW() - (NOTIFICATION_WIDTH + 10), NOTIFICATION_Y, ANIMATION_DURATION, 0, -1, function()
                -- After appearing, wait for DISPLAY_DURATION and hide
                timer.Simple(DISPLAY_DURATION, function()
                    if IsValid(frame) then
                        frame:MoveTo(NOTIFICATION_X_START, NOTIFICATION_Y, ANIMATION_DURATION, 0, -1, function()
                            if IsValid(frame) then
                                frame:Remove()
                            end
                        end)
                    end
                end)
            end)
        end
    
        -- Listen for network messages to show notifications
        net.Receive("ShowNotification", function()
            local text = net.ReadString()
            local model = net.ReadString()
            CreateNotification(text, model)
        end)
    
        -- Optional: Local console command for testing notifications
        concommand.Add("show_notification_client", function()
            CreateNotification("Это тестовое уведомление.", "models/player/alyx.mdl")
        end)
    end
    

    Server-Side Refactored Script (init.lua)

    if SERVER then
        util.AddNetworkString("ShowNotification")
    
        -- Constants
        local DEFAULT_MODEL = "models/player/alyx.mdl"
        local VALID_MODEL_PREFIX = "^models/"
    
        -- Whitelisted Models (Optional)
        local WHITELISTED_MODELS = {
            ["models/player/alyx.mdl"] = true,
            ["models/player/kleiner.mdl"] = true,
            ["models/player/mossman.mdl"] = true, -- Add more as needed
        }
    
        -- Helper function to send chat/console messages
        local function NotifySender(ply, message)
            if IsValid(ply) then
                ply:ChatPrint(message)
            else
                print(message)
            end
        end
    
        -- Function to send a notification to a player
        local function SendNotification(ply, text, modelPath)
            net.Start("ShowNotification")
                net.WriteString(text)
                net.WriteString(modelPath)
            net.Send(ply)
        end
    
        -- Function to validate Steam ID format
        local function IsValidSteamID(sid)
            return string.match(sid, "^STEAM_[0-5]:%d:%d+$") ~= nil
        end
    
        -- Function to validate model path against whitelist
        local function IsWhitelistedModel(modelPath)
            return WHITELISTED_MODELS[modelPath] or false
        end
    
        -- Console command to send notifications
        -- Usage: show_notification_server <steam_id> <text> [<model_path>]
        concommand.Add("show_notification_server", function(ply, cmd, args)
            -- Check if the command is run by a player and if they're admin
            if IsValid(ply) and not ply:IsAdmin() then
                ply:ChatPrint("У вас нет прав для использования этой команды.")
                return
            end
    
            -- Minimum required arguments: Steam ID and text
            if #args < 2 then
                local usageMsg = "Использование: show_notification_server <steam_id> <текст> [<путь_к_модели>]"
                NotifySender(ply, usageMsg)
                return
            end
    
            local steamID = args[1]
    
            -- Validate Steam ID format
            if not IsValidSteamID(steamID) then
                local errorMsg = "Неверный формат Steam ID. Пример: STEAM_0:1:123456"
                NotifySender(ply, errorMsg)
                return
            end
    
            -- Extract text and optional model path
            table.remove(args, 1) -- Remove Steam ID from args
    
            local model = DEFAULT_MODEL
            -- Check if the last argument is a model path
            if string.find(args[#args], VALID_MODEL_PREFIX) then
                local potentialModel = args[#args]
                if IsWhitelistedModel(potentialModel) then
                    model = potentialModel
                else
                    local warnMsg = "Указанная модель не разрешена. Используется модель по умолчанию."
                    NotifySender(ply, warnMsg)
                end
                table.remove(args, #args)
            end
    
            local text = table.concat(args, " ")
    
            -- Find the player by Steam ID
            local target = player.GetBySteamID(steamID)
    
            if target and target:IsValid() then
                SendNotification(target, text, model)
                local successMsg = "Уведомление отправлено игроку " .. target:Nick()
                NotifySender(ply, successMsg)
            else
                local notFoundMsg = "Игрок с Steam ID \"" .. steamID .. "\" не найден или не онлайн."
                NotifySender(ply, notFoundMsg)
            end
        end)
    end
    

    5. Profiling and Performance Optimization

    a. Client-Side Performance

    • VGUI Creation Overhead:

      • Issue: Creating and destroying VGUI panels frequently can cause performance drops.
      • Solution: Implement panel pooling or reuse existing panels by hiding and showing them instead of creating new instances each time.
    • Model Rendering:

      • Issue: Rendering models, especially with animations, can be CPU/GPU intensive.
      • Solution: Limit the number of simultaneous notifications or simplify the model rendering (e.g., reduce FPS of model animations).
    • Animation Timings:

      • Issue: Overlapping animations or too many simultaneous timers can strain client performance.
      • Solution: Throttle notifications or queue them to prevent too many at once.

    b. Server-Side Performance

    • Steam ID Resolution:

      • Issue: player.GetBySteamID may have performance implications if called excessively.
      • Solution: Cache frequently used player references or ensure that the command isn't abused to spam notifications.
    • Model Path Validation:

      • Issue: Checking against a large whitelist can be time-consuming.
      • Solution: Optimize the data structure (e.g., using a table with model paths as keys for O(1) lookups, as done in the refactored script).

    c. Profiling Tools and Techniques

    • Benchmarking VGUI Creation:

      • Use Lua's debug library to measure the time taken for panel creation and destruction.
      • Example:
        local startTime = SysTime()
        -- VGUI creation code
        local endTime = SysTime()
        print("VGUI creation took", endTime - startTime, "seconds")
        
    • Monitoring Model Panel Performance:

      • Profile client performance when multiple DModelPanel instances are active.
      • Use GMod's built-in performance tools and external profiling tools if necessary.
    • Server Command Abuse Prevention:

      • Implement rate limiting on the show_notification_server command to prevent spamming:
        local commandUsage = {}
        
        concommand.Add("show_notification_server", function(ply, cmd, args)
            local identifier = IsValid(ply) and ply:SteamID() or "console"
            commandUsage[identifier] = commandUsage[identifier] or { count = 0, lastUse = 0 }
        
            local currentTime = CurTime()
            if currentTime - commandUsage[identifier].lastUse < 1 then
                NotifySender(ply, "Пожалуйста, подождите перед повторным использованием команды.")
                return
            end
        
            commandUsage[identifier].count = commandUsage[identifier].count + 1
            commandUsage[identifier].lastUse = currentTime
        
            -- Existing command logic
        end)
        

    6. Additional Enhancements

    • Localization:

      • Implement a localization system to support multiple languages.
      • Example:
        local LANG = {
            ["notification_sent"] = "Уведомление отправлено игроку %s",
            ["invalid_steamID"] = "Неверный формат Steam ID. Пример: STEAM_0:1:123456",
            -- Add more entries as needed
        }
        
        -- Use it like:
        local message = string.format(LANG["notification_sent"], target:Nick())
        
    • Configuration Files:

      • Move constants and whitelisted models to separate configuration files for easier management.
    • Notification Stacking:

      • Adjust notification positioning to stack multiple notifications without overlapping, possibly animating them from bottom to top.
    • Persistent Notifications:

      • Implement a system to keep notifications persistent across sessions or respawns if necessary.
    • User Interface Enhancements:

      • Add icons, different notification types (info, warning, error), or interactivity to the notifications.

    Conclusion

    The provided scripts are functional for sending and displaying notifications in a GMod environment. However, by implementing the above audit suggestions, refactoring, and optimizations, you can enhance the security, performance, and maintainability of your code. Additionally, considering user experience enhancements and future scalability will make your addon more robust and user-friendly.

    If you have any specific areas you'd like further assistance with or additional features to implement, feel free to ask!