В Source 1 сущности имели два типа свойств: send props (синхронизируемые с клиентами) и data props (только на сервере). Source 2 упростил это, объединив их в единую систему схем. Схемы определяют структуру и свойства всех игровых объектов, и многие поля схем автоматически передаются по сети.
Схемы позволяют вам получать доступ и изменять свойства любой сущности или объекта в Source 2, включая здоровье, позицию, скорость, модель, команду и бесчисленное количество других атрибутов. Когда вы изменяете сетевые поля схем с установленным changeState в true, изменения автоматически синхронизируются с клиентами.
Версия с handle (например, GetEntSchema): Работает с handle сущностей; используйте это по возможности
Версия с указателем (например, GetEntSchema2): Работает с необработанными указателями; используйте только когда handle не могут быть сгенерированы (некоторые схемы не основаны на сущностях)
Всегда предпочитайте handle сущностей, если только вы не работаете с объектами схем, не являющимися сущностями.
Вот простой пример чтения и изменения здоровья игрока. Здоровье хранится в пешке игрока (теле в мире), а не в контроллере, поэтому пример сначала получает handle пешки из поля m_hPlayerPawn контроллера:
c#
c++
python
go
js
lua
using Plugify;
using s2sdk;
using static s2sdk.s2sdk;
public unsafe class Sample : Plugin
{
public void OnPluginStart()
{
AddConsoleCommand("set_health", "Sets player health to 200",
ConVarFlag.LinkedConcommand | ConVarFlag.Release,
(caller, context, arguments) =>
{
if (caller == -1) return ResultType.Handled;
// Controller handle from the slot, then the pawn handle
int controller = PlayerSlotToEntHandle(caller);
int pawn = GetEntSchemaEnt(controller, "CCSPlayerController", "m_hPlayerPawn", 0);
// Set the caller's health to 200
SetEntSchema(pawn, "CBaseEntity", "m_iHealth", 200, true, 0);
// Read back the health
int health = (int)GetEntSchema(pawn, "CBaseEntity", "m_iHealth", 0);
PrintToServer($"Player health set to {health}\n");
return ResultType.Handled;
}, HookMode.Post);
}
}
#include <format>
#include <plg/plugin.hpp>
#include <s2sdk/s2sdk.hpp>
using namespace s2sdk;
class Sample : public plg::Plugin {
public: plg::PluginResult OnPluginStart() override {
auto flags = static_cast<ConVarFlag>(
static_cast<int64_t>(ConVarFlag::LinkedConcommand) |
static_cast<int64_t>(ConVarFlag::Release));
AddConsoleCommand("set_health", "Sets player health to 200", flags,
[](int32_t caller, ConCommandContext context, const plg::vector<plg::string>& arguments) -> ResultType {
if (caller == -1) return ResultType::Handled;
// Controller handle from the slot, then the pawn handle
int32_t controller = PlayerSlotToEntHandle(caller);
int32_t pawn = GetEntSchemaEnt(controller, "CCSPlayerController", "m_hPlayerPawn", 0);
// Set the caller's health to 200
SetEntSchema(pawn, "CBaseEntity", "m_iHealth", 200, true, 0);
// Read back the health
int64_t health = GetEntSchema(pawn, "CBaseEntity", "m_iHealth", 0);
PrintToServer(std::format("Player health set to {}\n", health).c_str());
return ResultType::Handled;
}, HookMode::Post);
return {};
}
};
from plugify.plugin import Plugin
from plugify.pps import s2sdk as s2
class Sample(Plugin):
def plugin_start(self):
flags = s2.ConVarFlag.LinkedConcommand | s2.ConVarFlag.Release
def set_health_cmd(caller, context, arguments):
if caller == -1:
return s2.ResultType.Handled
# Controller handle from the slot, then the pawn handle
controller = s2.PlayerSlotToEntHandle(caller)
pawn = s2.GetEntSchemaEnt(controller, "CCSPlayerController", "m_hPlayerPawn", 0)
# Set the caller's health to 200
s2.SetEntSchema(pawn, "CBaseEntity", "m_iHealth", 200, True, 0)
# Read back the health
health = s2.GetEntSchema(pawn, "CBaseEntity", "m_iHealth", 0)
s2.PrintToServer(f"Player health set to {health}\n")
return s2.ResultType.Handled
s2.AddConsoleCommand("set_health", "Sets player health to 200", flags,
set_health_cmd, s2.HookMode.Post)
package main
import (
"fmt"
"github.com/fr0nch/go-plugify-s2sdk/v2"
"github.com/untrustedmodders/go-plugify"
)
func onPluginStart() error {
flags := s2sdk.ConVarFlag_LinkedConcommand | s2sdk.ConVarFlag_Release
s2sdk.AddConsoleCommand("set_health", "Sets player health to 200", flags,
func(caller int32, context s2sdk.ConCommandContext, arguments []string) s2sdk.ResultType {
if caller == -1 {
return s2sdk.ResultType_Handled
}
// Controller handle from the slot, then the pawn handle
controller := s2sdk.PlayerSlotToEntHandle(caller)
pawn := s2sdk.GetEntSchemaEnt(controller, "CCSPlayerController", "m_hPlayerPawn", 0)
// Set the caller's health to 200
s2sdk.SetEntSchema(pawn, "CBaseEntity", "m_iHealth", 200, true, 0)
// Read back the health
health := s2sdk.GetEntSchema(pawn, "CBaseEntity", "m_iHealth", 0)
s2sdk.PrintToServer(fmt.Sprintf("Player health set to %d\n", health))
return s2sdk.ResultType_Handled
}, s2sdk.HookMode_Post)
return nil
}
func init() {
plugify.NewPlugin("sample", onPluginStart, nil, nil)
}
import { Plugin } from 'plugify';
import * as s2 from ':s2sdk';
export class Sample extends Plugin {
pluginStart() {
const flags = s2.ConVarFlag.LinkedConcommand | s2.ConVarFlag.Release;
s2.AddConsoleCommand("set_health", "Sets player health to 200", flags,
(caller, context, arguments) => {
if (caller === -1) return s2.ResultType.Handled;
// Controller handle from the slot, then the pawn handle
const controller = s2.PlayerSlotToEntHandle(caller);
const pawn = s2.GetEntSchemaEnt(controller, "CCSPlayerController", "m_hPlayerPawn", 0);
// Set the caller's health to 200
s2.SetEntSchema(pawn, "CBaseEntity", "m_iHealth", 200, true, 0);
// Read back the health
const health = s2.GetEntSchema(pawn, "CBaseEntity", "m_iHealth", 0);
s2.PrintToServer(`Player health set to ${health}\n`);
return s2.ResultType.Handled;
}, s2.HookMode.Post);
}
}
local plugify = require 'plugify'
local Plugin = plugify.Plugin
local s2 = require 's2sdk'
local Sample = {}
setmetatable(Sample, { __index = Plugin })
function Sample:plugin_start()
local flags = s2.ConVarFlag.LinkedConcommand | s2.ConVarFlag.Release
s2.AddConsoleCommand("set_health", "Sets player health to 200", flags,
function(caller, context, arguments)
if caller == -1 then return s2.ResultType.Handled end
-- Controller handle from the slot, then the pawn handle
local controller = s2.PlayerSlotToEntHandle(caller)
local pawn = s2.GetEntSchemaEnt(controller, "CCSPlayerController", "m_hPlayerPawn", 0)
-- Set the caller's health to 200
s2.SetEntSchema(pawn, "CBaseEntity", "m_iHealth", 200, true, 0)
-- Read back the health
local health = s2.GetEntSchema(pawn, "CBaseEntity", "m_iHealth", 0)
s2.PrintToServer(string.format("Player health set to %d\n", health))
return s2.ResultType.Handled
end, s2.HookMode.Post)
end
local M = {}
M.Sample = Sample
return M
Некоторые поля схем являются массивами. Используйте параметр element для доступа к определенным индексам массива:
// Get array size
int arraySize = GetEntSchemaArraySize(entityHandle, "SomeClass", "m_arrayField");
// Access array elements (element is the last parameter)
for (int i = 0; i < arraySize; i++)
{
int value = (int)GetEntSchema(entityHandle, "SomeClass", "m_arrayField", i);
PrintToServer($"Array[{i}] = {value}\n");
}
// Set array element
SetEntSchema(entityHandle, "SomeClass", "m_arrayField", 42, true, 2); // Set index 2 to 42
Когда true, помечает поле как измененное и запускает сетевую синхронизацию с клиентами. Устанавливайте в true при изменении сетевых полей, false для изменений только на сервере.
Используется методами data (SetEntData*, ChangeEntityState), чтобы отправить изменение по сети. Передавайте значение GetSchemaChainOffset(className): -1 для обычного класса сущности, смещение >= 0, когда класс встроен через сетевой chainer, -2 для классов, не являющихся сущностями.
using System.Numerics;
using Plugify;
using s2sdk;
using static s2sdk.s2sdk;
public unsafe class Teleport : Plugin
{
public void OnPluginStart()
{
AddConsoleCommand("teleport", "Teleport to coordinates",
ConVarFlag.LinkedConcommand | ConVarFlag.Release,
Command_Teleport, HookMode.Post);
}
public ResultType Command_Teleport(int caller, ConCommandContext context, string[] arguments)
{
if (caller == -1) return ResultType.Handled;
if (arguments.Length < 4)
{
PrintToServer("Usage: teleport <x> <y> <z>\n");
return ResultType.Handled;
}
int controller = PlayerSlotToEntHandle(caller);
int pawn = GetEntSchemaEnt(controller, "CCSPlayerController", "m_hPlayerPawn", 0);
float x = float.Parse(arguments[1]);
float y = float.Parse(arguments[2]);
float z = float.Parse(arguments[3]);
// The position lives in the scene node, not in a schema field of the entity,
// so move the pawn with TeleportEntity. A NaN vector leaves that value unchanged.
Vector3 newPosition = new Vector3(x, y, z);
Vector3 keepAngles = new Vector3(float.NaN);
// Also reset velocity to prevent momentum
TeleportEntity(pawn, newPosition, keepAngles, Vector3.Zero);
PrintToServer($"Teleported to ({x}, {y}, {z})\n");
return ResultType.Handled;
}
}
using Plugify;
using s2sdk;
using static s2sdk.s2sdk;
public unsafe class ModelChanger : Plugin
{
public void OnPluginStart()
{
AddConsoleCommand("setmodel", "Change player model",
ConVarFlag.LinkedConcommand | ConVarFlag.Release,
Command_SetModel, HookMode.Post);
}
public ResultType Command_SetModel(int caller, ConCommandContext context, string[] arguments)
{
if (caller == -1) return ResultType.Handled;
if (arguments.Length < 2)
{
PrintToServer("Usage: setmodel <model_path>\n");
return ResultType.Handled;
}
int controller = PlayerSlotToEntHandle(caller);
int pawn = GetEntSchemaEnt(controller, "CCSPlayerController", "m_hPlayerPawn", 0);
// The model name is not a plain string field of the entity, so use SetEntityModel
string modelPath = arguments[1];
SetEntityModel(pawn, modelPath);
PrintToServer($"Model changed to: {modelPath}\n");
return ResultType.Handled;
}
}
Для критичного по производительности кода вы можете использовать необработанные смещения:
// Get offset once and cache it
int healthOffset = GetSchemaOffset("CBaseEntity", "m_iHealth");
int chainOffset = GetSchemaChainOffset("CBaseEntity");
// Use offset directly for better performance
SetEntData(pawnHandle, healthOffset, 100, 4, true, chainOffset);
int health = (int)GetEntData(pawnHandle, healthOffset, 4);
Для объектов схем, не являющихся сущностями (когда handle недоступны):
// Example: Working with a non-entity schema object
nint objectPointer = GetSomeNonEntityPointer();
// Use the '2' version of functions
SetEntSchema2(objectPointer, "SomeClass", "m_someField", 42, true, 0);
int value = (int)GetEntSchema2(objectPointer, "SomeClass", "m_someField", 0);
// Update specific field
NetworkStateChanged(pawnHandle, "CBaseEntity", "m_iHealth");
// Or using offset
int offset = GetSchemaOffset("CBaseEntity", "m_iHealth");
int chainOffset = GetSchemaChainOffset("CBaseEntity");
ChangeEntityState(pawnHandle, offset, chainOffset);
Позиция и поворот (m_vecAbsOrigin, m_angAbsRotation) принадлежат CGameSceneNode, а не сущности: чтобы переместить сущность, используйте TeleportEntity. Имя модели принадлежит CModelState: используйте SetEntityModel.
Обратитесь к дампам схем для полного списка доступных классов и полей.