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
Assistant
lua
-- Регистрация сетевого сообщения
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
Your Lua scripts for creating and handling in-game notifications in Garry's Mod (GMod) are well-structured and cover both client-side and server-side functionalities effectively. Below is a detailed review of your code, highlighting strengths, potential issues, and suggestions for improvements.
Client-Side Script Review
Features Implemented:
Notification Panel Creation:
Creates a DPanel with customizable size and position.
Adds a semi-transparent gray background with rounded corners.
Displays dynamic text and a 3D model.
Model Handling:
Sets a default model if none is provided.
Adjusts the camera to fit the model correctly.
Adds a continuous rotation animation to the model.
Animation:
Smoothly animates the panel sliding in from the right.
Automatically removes the panel after 5 seconds with a slide-out animation.
Networking:
Listens for the "ShowNotification" network message to display notifications.
Testing:
Provides a console command (show_notification_client) for local testing.
Strengths:
Modularity: The CreateNotification function encapsulates all logic related to creating and displaying the notification, making it reusable.
User Experience: Smooth animations enhance the visual appeal and ensure that notifications are not intrusive.
Default Settings: Providing default values (like the model path) ensures that the notification works even if some parameters are missing.
Flexibility: The ability to specify different models allows for versatile notifications catering to various in-game situations.
Potential Issues & Suggestions:
Model Validation:
Issue: If an invalid model path is provided, the DModelPanel may fail to load the model, leading to potential runtime errors or broken UI elements.
Suggestion: Add validation to check if the model path exists before setting it. You can use util.IsValidModel(modelPath) to verify the model's validity.
Handling Large Text:
Issue: While SetWrap(true) is enabled, very long texts might not display properly within the fixed size of the label.
Suggestion: Consider dynamically adjusting the size of the notification panel based on the text length or implementing a scrolling text feature for excessively long messages.
Concurrency:
Issue: Rapidly sending multiple notifications could overwhelm the UI, leading to overlapping panels or performance issues.
Suggestion: Implement a queue system where notifications are displayed one after another or limit the number of concurrent notifications.
Localization:
Issue: Currently, text is hardcoded in Russian. If you plan to support multiple languages, this might pose a challenge.
Suggestion: Use a localization system to handle multi-language support, making your notifications more versatile.
Accessibility:
Issue: The color scheme (gray background with white text) might not be optimal for all players, especially those with visual impairments.
Suggestion: Allow customization of colors or provide settings for different themes to enhance accessibility.
Performance:
Issue: Continuously rotating models can be performance-intensive, especially if multiple notifications are displayed simultaneously.
Suggestion: Optimize the rotation logic or limit the use of DModelPanel animations based on performance metrics.
Server-Side Script Review
Features Implemented:
Network Registration:
Registers the "ShowNotification" network string for client-server communication.
Notification Sending:
Defines a function SendNotification to send notifications to specific players with text and model path.
Steam ID Validation:
Implements a function IsValidSteamID to validate the format of Steam IDs.
Console Command:
Adds a server-side console command (show_notification_server) to send notifications to players using their Steam ID.
Includes permission checks to ensure only admins can use the command.
Strengths:
Security: Restricting the show_notification_server command to admins prevents unauthorized usage.
Validation: Thoroughly checks the format of Steam IDs before attempting to send notifications, reducing the chance of errors.
Feedback: Provides clear chat or console messages to inform the user about the success or failure of their actions.
Potential Issues & Suggestions:
Steam ID Formats:
Issue: The IsValidSteamID function only checks for the classic STEAM_X:Y:Z format. With the introduction of new identifiers (e.g., SteamID64), this might limit functionality.
Suggestion: Consider supporting multiple Steam ID formats by expanding the validation function or providing alternative methods to identify players (e.g., using Player( identifier ) with SteamID64).
Error Handling:
Issue: While the script checks for player validity and online status, it doesn't handle scenarios where the network message fails to send.
Suggestion: Implement additional error handling or logging to capture and address issues related to network failures.
Model Path Validation:
Issue: The server-side script allows any model path to be sent to the client without validation, which might lead to security or integrity issues.
Suggestion: Validate the model paths on the server-side to ensure only authorized models can be used in notifications. This prevents potential misuse or exploits.
Command Argument Parsing:
Issue: The command currently expects the model path as the last argument if it starts with "models/". This might lead to incorrect parsing if the text includes a path-like string.
Suggestion: Use explicit flags or parameters to distinguish between text and model path arguments. For example, show_notification_server <steam_id> <text> -model <model_path>.
Internationalization:
Issue: Error and informational messages are in Russian. If your server caters to an international audience, this might exclude non-Russian speakers.
Suggestion: Implement localization for server messages or allow server admins to customize messages as needed.
Asynchronous Operations:
Issue: Currently, all operations are synchronous. In a high-traffic server, this might lead to performance bottlenecks.
Suggestion: Consider implementing asynchronous handling for sending notifications, especially if integrating with external systems or databases in the future.
General Recommendations
Code Documentation:
Suggestion: Add comprehensive comments and documentation to your scripts. This aids in maintenance and helps other developers understand your code's functionality and intent.
Modularization:
Suggestion: Separate your client and server scripts into different files or modules for better organization, especially if your project scales.
Testing:
Suggestion: Implement unit tests or integrate with automated testing frameworks to ensure your notification system works as expected under various scenarios.
Security:
Suggestion: Always be cautious about the data sent between the server and client. Ensure that all inputs are validated and sanitized to prevent potential exploits.
Performance Optimization:
Suggestion: Profile your scripts to identify and optimize any performance-critical sections, ensuring that your notification system remains responsive and efficient.
User Customization:
Suggestion: Allow players to customize notification settings (e.g., enable/disable notifications, choose themes) to enhance user experience and accessibility.
Conclusion
Your implementation provides a solid foundation for an in-game notification system in GMod. By addressing the potential issues and incorporating the suggested improvements, you can enhance the reliability, security, and user experience of your notifications. Keep iterating and testing to ensure that the system meets the needs of your server and its players effectively.
If you have specific questions or encounter particular issues while implementing or testing these scripts, feel free to ask for more targeted assistance!