Wikia

GoRap Wiki

Wire Expression2

Обсуждение0
67статей на этой вики
Stub.png Эта статья не переведена до конца. Пожалуйста помогите нам доперевести ее.
Спасибо!

ОсобенностиПравить

Wire Expression 2Править

Уникальный чип, функцию которого может задать сам игрок с помощью собственного языка программирования.

СинтаксисПравить

Синтаксис Expression 2 сильно изменился со времен прошлого Expression Chip, придется изучить немного больше команд, но это сделает ваши постройки намного более функциональными. Помните что как правило существует несколько способов написания кода, и задача может быть решена несколькими путями.

Синтаксис Пример Упрощенный Описание
##this is comment Все, что находится за знаком # считается комментарием и не учитывается при обработке кода
if () {} else {} if (A) {D=B} else {D=C} if (A) {D=B} если A истина то выполняем первую операцию, иначе вторую. else {} не обязателен, например: "if (A) {C=B}"
elseif () {} elseif (A) {B = C} Впереди обязательно должен быть if или elseif. Дополнительная проверка в случае ложности исходного утверждения
~ if(~Time & Time == 0) {DO stuff} Изменялось ли значение на входе между выполнениями?
$ Opitch = Pitch + ($Pitch *3) Возвращает разницу между выполнениями в виде числа. (Работает только с объявленными переменными типа number, vector, and angle)
++ if(Count == 2 {Count++} Count = Count + 1 Прибавляет 1 к заданной переменной.
-- if(Count == 3){Count--} Count = Count - 1 Вычитает 1 из заданной переменной.
+= if(Count == 4){Count += 2} Count = Count + 2 Прибавляет число после += к заданной переменной.
-= if(Count == 5) {Count -= 2} Count = Count - 2 Вычитает число после -= из заданной переменной.
( ? : ) D = (A ? B : C) Если A истина то возвращает B иначе C.
I if (A I B) {C = 1} Если A или B истина C=1.
& if (A & B) {C = 1} Если A и B истина C=1.
 ! if (!A) {B = 1} Должно предшествовать число. Возвращает 1 если A ложно (эквивалентно "A == 0").
Должно предшествовать число.
-> ->Input or ->Output Если вы используете его на входе, он возвращает 1, когда вход подсоединяется к чему либо. Если вы используете его на выходе, он возвращает количество входов присоединённых на выход.
#ifdef #ifdef entity():setAlpha(number) Проверяет может ли данная функция выполняться на сервере.
#else #else entity():setModel(string) Должно предшествовать #ifdef. Если данная функция не может использоваться на сервере запустится код после #else...
#endif #endif Должно предшествовать #ifdef или #else .Закрывает выражение #ifdef.

ПеременныеПравить

В E2, все входы, выходы и переменные должны быть объявлены с заглавной буквы:

Синтаксис Описание
@persist variable Это не будет работать, так как переменная "variable" объявлена со строчной буквы.
@persist Variable Это будет работать, так как переменная "Variable" начинается с заглавной буквы.

Выражение @triggerПравить

Выражение @trigger может выборочно разрешать и запрещать входам вызывать выполнение кода. Возможные значения: all/none, или список разрешенных входов

Синтаксис Описание
@trigger all всё по старому, изменение значения на входах всегда вызывает выполнение кода
@trigger none изменение значения на входах никогда не вызывает выполнение кода, его вызывает только таймер, и.т.п. функции
@trigger Time Button выполнение кода вызывается только при изменении значений на входах Time и Button

ЦиклыПравить

Синтаксис Пример Описание
while () {}while (A) {B++}Любые инструкции в фигурных скобках будет повторяться, пока условие в круглых скобках истинно. Если условие ложно, инструкции будут пропущены и E2 будет продолжаться с конца цикла. Заметим, что условие проверяется только в самом начале каждого цикла.
for () {} for (I = A, B[, C]) {} Добавляет значение C переменной для каждой итерации, пока она равна значению B. Если шаг C не указан, то он будет установлен на единицу. Обратите внимание, что А и В вычисляются только один раз - если они рассчитываются из переменных, что цикл устанавливает новые значения, это не изменит число итераций.
foreach () {}foreach(K,V:type=Table) {}Проверяет  каждый элемент указанного типа в таблице. Назначает ключ к К и значение V. Элементы, которые не имеют определенного типа будут пропущены. Элементы могут быть добавлены, удалены или изменены, однако добавляемые элементы не будут обрабатываться в текущем цикле. Только цикл по строке индексов при использовании таблицы.
continueif (A) {continue}Может быть использовано только в while/for/foreach цикле. Эта команда позволяет немедленно вернуться к началу цикла, пропуская следующие инструкции.
breakif (A) {break}Может быть использовано только в while/for/foreach цикле. Эта команда позволяет немедленно вернуться к выходу из цикла, пропуская следующие инструкции.

ПроизводительностьПравить

Были проведены некоторые тесты в игре:

~3.000.000/сек арифметических операций (+-*/) на числах, 2000 операций, 200 выполнений за 0.13сек

~850.000/сек арифметических операций (+-*/) на векторах, 2000 операций, 100 выполнений за 0.23сек

Горячие Клавиши РедактораПравить

Ctrl-Пробел Проверить (и переместить курсор на ошибку)
Ctrl-S Сохранить
Ctrl-Z Отменить
Ctrl-Y Вернуть
Ctrl-X Вырезать
Ctrl-C Копировать
Ctrl-V Вставить
Ctrl-A Выделить Всё
Ctrl-Up Прокрутить Вверх
Ctrl-Down Прокрутить Вниз
Ctrl-Left Прокрутить Влево
Ctrl-Right Прокрутить Вправо

Консольные командыПравить

Команда Описание
wire_expression2_model <model>Вручную меняет модель чипа
wire_expression2_reloadПерезагружает все расширения для E2, полезно для отладки своих расширений. Помните, что клиентские файлы в мультиплеере берутся из кэша g-mod.
wire_expression2_debug 0/1Включает режим отладки, который может быть полезен для разработчиков. Необходимо ввести "wire_expression2_reload" после изменения, чтобы сработало.
wire_expression2_extension_enable <extension>Включить определенное расширение
wire_expression2_extension_disable <extension>Выключить определенное расширение
wire_expression2_unlimited 0/1Включить/выключить ограничения по производительности

ТипыПравить

Expression2 использует несколько типов данных. По понятным причинам, тут только верхушка всего айсберга.

Сокращение Типы
N.png Number(Числа)
V2 / V / V4 2D / 3D / 4D Vector(Векторы)
A Angle(Углы)
S String(Строки)
E Entity(Объекты)
R Array(Массивы)
T Table(Таблицы)
RD Ranger Data(Рейнджеры)
B Bone(Кости)
M2 / M / M4 2x2 / 3x3 / 4x4 Matrix(Матрицы)
XWL Wirelink
C Комплексные числа
Q Кватернионы

ЧислаПравить

ОписаниеПравить

Производит операции над числами

КомандыПравить

Функция Возвращает Описание
N.png + N.png N.png Сложение
N.png - N.png N.png Вычитание
N.png * N.png N.png Умножение
N.png / N.png N.png Деление
N.png ^ N.png N.png Возведение в степень (2 ^ 3 = 8)
N.png % N.png N.png Остаток от деления арумента 1 на аргумент 2. Примечание "-1 % 3 = 2"
mod(N.png, N.png) N.png Остаток от деления арумента 1 на аргумент 2. Примечание "mod(-1, 3) = -1"
sqrt(N.png) N.png Возвращает квадратный корень числа
cbrt(N.png) N.png Возвращает кубический корень числа
root(N.png, N.png) N.png Возвращает корень первого числа
e() N.png Возвращает число Эйлера
exp(N.png) N.png Возводит число Эйлера в степень аргумента (можно и e()^N.png, однако так быстрее)
ln(N.png) N.png Возвращает логарифм числа N.png по основанию e (число Эйлера)
log2(N.png) N.png Возвращает логарифм числа N.png по основанию 2 (двоичный)
log10(N.png) N.png Возвращает логарифм числа N.png по основанию 10(десятичный)
log(N.png,N.png) N.png Возвращает логарифм первого аргумента по основанию второго
abs(N.png) N.png Возвращает модуль числа
ceil(N.png) N.png Округляет аргумент до ближайшего большего целого числа [ceil(5.5) = 6]
ceil(N.png,N.png) N.png Округляет аргумент с десятичной точностью до второго аргумента [ceil(5.05) = 5.1]
floor(N.png) N.png Округляет аргумент до ближайшего меньшего целого числа [floor(5.5) =5]
floor(N.png,N.png) N.png Округляет аргумент с десятичной точностью до второго аргумента [floor(5.14) = 5.1]
round(N.png) N.png Округление [round(5.5) = 6; round(5.4) = 5]
round(N.png,N.png) N.png Округление с десятичной точностью до второго аргумента
int(N.png) N.png Возвращает целую часть числа (как floor)
frac(N.png) N.png Возвращает дробную часть числа (как floor)
clamp(N.png,N.png,N.png) N.png Если Arg1 <= Arg2 (минимальное) возвращает Arg2; если Arg1 >= Arg3 (максимальное) возвращает Arg3; иначе возвращает Arg1.
inrange(N.png,N.png2,N.png3) N.png Возвращает 1 если N.png находится в интервале [N.png2; N.png3], иначе 0.
sign(N.png) N.png Возвращает знак числа (-1,0,1) [sign(N.png) = N.png / abs(N.png) ]
min(N.png,N.png) N.png Возвращает значение минимального аргумента
min(N.png,N.png,N.png) N.png Возвращает значение минимального аргумента
min(N.png,N.png,N.png,N.png) N.png Возвращает значение минимального аргумента
max(N.png,N.png) N.png Возвращает значение максимального аргумента
max(N.png,N.png,N.png) N.png Возвращает значение максимального аргумента
max(N.png,N.png,N.png,N.png) N.png Возвращает значение максимального аргумента
random() N.png Возвращает случайное число с плавающей точкой между 0 и 1 [0 <х <1]
random(N.png) N.png Возвращает случайное число с плавающей точкой между 0 и указанным значением [0 <= X <]
random(N.png,N.png) N.png Возвращает случайное число с плавающей точкой в указанном интервале [A < х < B]
randint(N.png) N.png Возвращает случайное целое число между 1 и указанным значением [1 <= x <= a ]
randint(N.png,N.png) N.png Возвращает случайное целое число в указанном интервале [a <= x <= b ]
pi() N.png Возвращает постоянную ПИ
toRad(N.png) N.png Переводит градусную меру угла в радианную
toDeg(N.png) N.png Переводит радианную меру угла в градусную
sin(N.png) N.png Возвращает синус числа N.png (из градусной меры)
cos(N.png) N.png Возвращает косинус числа N.png (из градусной меры)
tan(N.png) N.png Возвращает тангенс числа N.png (из градусной меры)
asin(N.png) N.png Возвращает арксинус числа N.png (из градусной меры)
acos(N.png) N.png Возвращает арккосинус числа N.png (из градусной меры)
atan(N.png) N.png Возвращает арктангенс числа N.png (из градусной меры)
sinh(N.png) N.png Возвращает гиперболический синус N.png (из градусной меры)
cosh(N.png) N.png Возвращает гиперболический косинус числа N.png (из градусной меры)
tanh(N.png) N.png Возвращает гиперболический тангенс числа N.png (из градусной меры)
sinr(N.png) N.png Возвращает синус числа N.png (из радианной меры)
cosr(N.png) N.png Возвращает косинус числа N.png (из радианной меры)
tanr(N.png) N.png Возвращает тангенс числа N.png (из радианной меры)
asinr(N.png) N.png Возвращает арксинус числа N.png (из радианной меры)
acosr(N.png) N.png Возвращает арккосинус числа N.png (из радианной меры)
atanr(N.png) N.png Возвращает арктангенс числа N.png (из радианной меры)
atanr(N.png,N.png) N.png Возвращает арктангенс аргументов (ARG1 / ARG2), в радианах. Эта функция учитывает положительные / отрицательные аргументы, и аргументы близкие к 0
sinhr(N.png) N.png Возвращает гиперболический синус числа N.png (из радианной меры)
coshr(N.png) N.png Возвращает гиперболический косинус числа N.png (из радианной меры)
tanhr(N.png) N.png Возвращает гиперболический тангенс числа N.png (из радианной меры)
A = B N.png Присваивание (присвоить переменной A число B)
A++ N.png Увеличить на 1 (добавить к A единицу, упрощенно "A += 1")
A-- N.png Уменьшить на 1 (вычисть из A единицу, упрощенно "A -= 1")
A += B N.png Увеличить на число (увеличить A на B, упрощенно "A = (A + B)")
A -= B N.png Уменьшить на число (уменьшить A на B, упрощенно "A = (A - B)")
A /= B N.png Делит A на B
A %= B N.png Присваивает A остаток деления A на B
A ^= B N.png Возводит A в степень B
A == B N.png A равно B?
A != B N.png А не равно В?
A > B N.png А больше В?
A < B N.png А меньше В?
A >= B N.png А больше или равно В?
A <= B N.png А меньше или равно В?

СтрокиПравить

ОписаниеПравить

Строки позволяют вам работать с текстом в E2. Необходимо для роты текстовых экранов.

Пример работыПравить

КомандыПравить

Создает строку из помещенной в кавычки, например,"text goes here" Доступны операторы равенства (==) и неравенства, также как и конкатенации(+), для объединения строк и чисел в любом порядке. Операция конкатенации возвращает строку. Первый символ строки имеет номер 1. Отрицательные индексы отсчитываются от конца строки, в которой последний символ -1. Положительные индексы привязаны к длине строки.

Функции Возвращает Описание
S:index(N.png) S Возвращает N-нный символ из строки
S:length() N.png Возвращает длину строки
S:upper() S Делает все буквы у строки большими
S:lower() S Делает все буквы у строки маленькими
S:sub(N.png,N.png) S Возвращает подстроку, начиная с первого аргумента и заканчивая вторым
S:left(N.png) S Возвращает первые N.png символов строки
S:right(N.png) S Возвращает последние N.png символов строки
S:find(S) N.png Возвращает 1 если в строке найдена подстрока S, или 0 если не найдена
S:find(S, N.png) N.png Возвращает 1 если в строке найдена подстрока S начиная с Nого символа, или 0 если не найдена
S:explode(S) R Разбивает строку через разделитель S и записывает результат в массив. Подробнее string.Explode
S:repeat(N.png) S Повторяет N раз, возвращает S
trim(S) S Trims away spaces at the beginning and end of a string
S:trimLeft() S Trims away opening spaces on the string
S:trimRight() S Trims away spaces at the end of a string
S:replace(1S,2S) S В строке S, находит все 1S, и заменяет их на 2S
S:reverse() S Возвращает перевернутую строку S
S:toNumber() N.png Переводит строку в числа
toString(N.png) S Переводит число N.png в строку. (Числа могут быть преобразованы в строку без этой функции)
toChar(N.png) S Возвращает ASCII-код из N.png, при условии что там помещен один знак.
toByte(S) N.png Возвращает ASCII-код от первого знака в начале строки.
toByte(S,N.png) N.png Возвращает ASCII-код знака из S, на позиции N.png
S:match(S2,N.png) R Запускает функцию string.match(S, S2, N) garrysmod и возвращает в виде массива.
S:match(S2) R Запускает функцию string.match(S, S2) garrysmod и возвращает в виде массива.
S:matchFirst(S2,N.png) S Запускает функцию string.match(S, S2, N) garrysmod и первое совпадение или пустую строку в случае ошибки.
S:matchFirst(S2) S Запускает функцию string.match(S, S2) garrysmod и первое совпадение или пустую строку в случае ошибки.

EntityПравить

ОписаниеПравить

Эти функции позволяют получать информацию и манипулировать объектами (такими как игроки или пропы), находящимися в игровом мире. Entity объекта можно получить несколькими способами: используя Target finder, Entity marker или специальными командами в самом E2.

Since the expression collects the data directly from the entity, it is much faster to handle calculations from within the E2 than having a beacon-sensor send its information to the gate.

A valid entity will return true in an if-statement. This is helpful for preventing LUA errors resulting from using entity commands on entities which have been destroyed.

Примеры работыПравить

КомандыПравить

Только операторы для объектов равны и не равны. Кроме того, объект будет возвращать <span style="color:rgb(0,0,0);font-

Функция  Возвращает Описание      |     Увеличить   
entity(N.png) E Возвращает объект, связанный по ID
owner() E Действие будет происходить с владельцем ( owner ) чипа. ( так же, как entity():owner() )
E:id() N.png Возвращает числовой идентификатор объекта
noentity() E Returns an invalid entity
E:type() S Возвращает тип объекта
E:model() S Возвращает модель объекта
E:owner() E Возвращает владельца чипа
E:name() S Возвращает имя чего-либо
E:steamID() S Возвращает Steam ID игрока (на данный момент с ошибками)
E:pos() V Возвращает позицию
E:eye() V Возвращает позицию взгляда игрока или же направление объекта в переднюю сторону
E:eyeTrace() RD Равносильно rangerOffset(16384, E:shootPos(), E:eye()), но быстрее (создает меньше лагов)
E:shootPos() V Возвращает позицию выстрела игрока
E:aimEntity() E Возвращает объект на который смотрит игрок
E:aimBone() B Возвращает кость на которую смотрит игрок
E:aimPos() V Возвращает позицию взгляда игрока (не сторону,в отличие от E:eye() )
E:aimNormal() V Returns a normalized directional vector perpendicular to the surface pointed at
E:frags() N.png Возвращает количество убийств игрока
E:team() N.png Возвращает  номер команды игрока
teamname(N.png) S Возвращает имя команды связанной с номером
E:forward() V Возвращает переднее направление объекта
E:right() V Возвращает правое направление объекта
E:up() V Возвращает верхнее направление объекта
E:vel() V Возвращает скорость объекта
E:velL() V Gets the local velocity of the entity
E:boxCenter() V Возвращает середину ограничивающей рамки объекта
E:boxMax() V Возвращает максимальную высоту ограничивающей рамки объекта(самый высокий угол)
E:boxMin() V Возвращает минимальную высоту ограничивающей рамки объекта(самый низкий угол)
E:boxSize() V Возвращает размер ограничивающей рамки объекта(длинна,ширина,высота)
E:toWorld(V) V Transforms from a vector local to E to a world vector.
E:toLocal(V) V Transforms from a world vector to a vector local to E.
E:toWorld(A) A Transforms from an angle local to E to a world angle.
E:toLocal(A) A Transforms from a world angle to an angle local to E.
E:angVel() A Gets the angular velocity of the entity
E:angVelVector() V Returns rotation axis, velocity and direction given as the vector's direction, magnitude and sense
E:angles() A Gets the pitch, yaw and roll of the entity
E:radius() N.png Возвращает размер объекта (хоть и не точно,но это полезно)
E:height() N.png Возвращает высоту игрока или NPC
E:bearing(V) N.png Gets the bearing from the entity to the vector
E:elevation(V) N.png Gets the elevation from the entity to the vector
E:direction(V) A Gets the elevation and bearing from the entity to the vector
E:health() N.png Возвращает здоровье объекта
E:armor() N.png Возвращает броню обьекта
E:mass() N.png Возвращает массу объекта
E:timeConnected() N.png Возвращает время в течении которого игрок находится на сервере
E:massCenter() V Возвращает массу середины объекта
E:massCenterL() V Gets the local Center of Mass of the entity
E:setMass(N.png) Устанавливает массу объекта (между 0.001 и 50,000)
E:inertia() V Gets the principal components of the entity's inertia tensor in the form ( Ixx, Iyy, Izz )
E:applyForce(V) К объекту применяется сила, заданная вектором
E:applyOffsetForce(V,V) Applies force to the entity according to the first vector from the location of the second
E:applyAngForce(A) Applies torque to the entity according to the given angle
E:applyTorque(V) Applies torque according to the given vector, representing the torque axis, magnitude and direction
E:isPlayer() N.png Является ли этот объект игроком?
E:isOnFire() N.png Этот объект горит?
E:isWeapon() N.png Этот объект оружие?
E:isNPC() N.png Является ли этот объект NPC?
E:isFrozen() N.png Заморожен ли этот объект?
E:isVehicle() N.png Этот объект это транспорт?
E:inVehicle() N.png Если объект игрок,то в транспорте ли он??
E:isWorld() N.png Это объект карты?
E:isOnGround() N.png Опирается ли объект на что-то?(работает только на игроков и NPC)
E:isUnderWater() N.png Этот объект под водой?
E:isPlayerHolding() N.png Держит ли игрок этот предмет?
E:isAlive() N.png Жив ли этот игрок или NPC?
E:isCrouch() N.png Игрок присел?
E:inNoclip() N.png Игрок в режиме хождения сквозь стены?
E:keyAttack1() N.png Нажимает ли игрок кнопку "огонь"?
E:keyAttack2() N.png Нажимает ли игрок кнопку "альтернативный огонь?
E:keyUse() N.png Нажимает ли игрок кнопку "использовать" 
E:hintDriver(S,N.png) N.png Displays a hint popup to the driver of vehicle E, with message S for N.png seconds (N.png being clamped between 0.7 and 7). Returns 1 if the hint has been sent.
E:printDriver(S) N.png Posts S to the chat of the driver of vehicle E. Returns 1 if the text was printed, 0 if not.
E:driver() E Returns the driver of the vehicle if there is one, nil otherwise
E:passenger() E Returns the passenger of the vehicle if there is one, in single seat pods this will return the driver.
E:lockPod(N.png) Значение 1 закрывает транспорт,значение 0 открывает
E:ejectPod() Выгоняет игрока из транспорта
E:killPod() Убивает игрока в транспорте
E:weapon() E Возвращает оружие которое сейчас держит игрок
E:clip1() N.png Возвращает количество патронов у игрока
E:clip2() N.png Возвращает количество альт.патронов
E:primaryAmmoType() S Возвращает тип обычных патронов 
E:secondaryAmmoType() S Возвращает тип альт.патронов
E:ammoCount(S) N.png Returns the amount of stored ammo of type S on player E, excluding current clip
E:removeTrails() Убирает хвосты/трейлы с объекта
E:setTrails(N.png,N.png,N.png,S,V,N.png) Задает объекту трейл, значения:(Начальный размер, Конечный размер,Длинна, Материал,Цвет(RGB),Прозрачность
E:lookupAttachment(string attachmentName) N.png Returns entity's attachment ID associated with attachmentName
E:attachmentPos(attachmentID) V Returns entity's attachment position associated with attachmentID
E:attachmentAng(attachmentID) A Returns entity's attachment angle associated with attachmentID
E:attachmentPos(string attachmentName) V Same as E:attachmentPos(E:lookupAttachment(attachmentName))

E:attachmentAng(string attachmentName) || A|| Same as E:attachmentAng(E:lookupAttachment(attachmentName))

ВекторыПравить

ОписаниеПравить

Vectors are now properly implemented in the Expression 2, which means that they are as easy to work with as numbers. For those that know what vectors are, and how to use them, this is a great tool for creating many things.

2D and 4D vectors are also supported by E2. These include all the standard functions of 3D vectors listed here. If you're doing 2D vector operations, you can now do things much more efficiently. 4D vectors work in conjunction with matrices, and can be used as homogeneous representations of 3D vectors.

Operational functions can be used between numbers and vectors, e.g. N*V. Note that operations cannot be performed between two vectors of different size, for example multiplication between a 2D and a 3D vector.

Related ExamplesПравить

КомандыПравить

Functions specific to 2D vectors

Команда Возвращает Описание
vec2(N.png,N.png) V2 Создает 2D вектор
vec2() V2 Same as vec2(0,0)
vec2(V) V2 Конвертирует 3D вектор в 2D (z опускается)
vec2(V4) V2 Конвертирует 4D вектор в 2D (z и w опускаются)
V2:cross(V2) N.png Gets the 2D vector cross product/wedge product
shift(V2) V2 Swaps the vector's x,y components
V2:rotate(N.png) V2 Поворачивает вектор на заданный аргумент N.png (из градусной меры)
V2:toAngle() N.png Returns the 2D angle of the vector (given in degrees, -180 to 180)
V:dehomogenized() V2 Converts a 2D homogeneous vector (x,y,w) into a 2D cartesian vector

3D Vector CommandsПравить

Functions specific to 3D vectors

Function Returns Description
vec(N.png,N.png,N.png) V Makes a 3D vector
vec() V Same as vec(0,0,0)
vec(V2) V Converts a 2D vector into a 3D vector (the z component is set to 0)
vec(V2,N.png) V Converts a 2D vector into a 3D vector (the z component is set to the second argument)
vec(V4) V Converts a 4D vector into a 3D vector (the w component is dropped)
vec(A) V Changes an angle variable into a vector variable
V:cross(V) V Gets the 3D vector cross product
shiftL(V) V Shifts the vector's components left: shiftL( x,y,z ) = ( y,z,x )
shiftR(V) V Shifts the vector's components right: shiftR( x,y,z ) = ( z,x,y )
V:rotate(A) V Gets the rotated vector
V:rotate(N.png,N.png,N.png) V Gets the rotated vector
V:toAngle() A Gets the angles of the vector
V4:dehomogenized() V Converts a 3D homogeneous vector (x,y,z,w) into a 3D cartesian vector
V:isInWorld() N.png Returns 1 if the position vector is within the world, 0 if not

4D Vector CommandsПравить

Functions specific to 4D vectors. From a mathematics standpoint these are treated as 4D Cartesian vectors, where the 4th component is referred to as "w".

Function Returns Description
vec4(N.png,N.png,N.png,N.png) V4 Makes a 4D vector
vec4() V4 Same as vec4(0,0,0,0)
vec4(V2) V4 Converts a 2D vector into a 4D vector (the z and w components are set to 0)
vec4(V2,N.png,N.png) V4 Converts a 2D vector into a 4D vector (the z and w components are set to the second and third arguments)
vec4(V2,V2) V4 Creates a 4D vector from two 2D vectors
vec4(V) V4 Converts a 3D vector into a 4D vector (the w component is set to 0)
vec4(V,N.png) V4 Converts a 3D vector into a 4D vector (the w component is set to the second argument)
shiftL(V4) V4 Shifts the vector's components left: shiftL( x,y,z,w ) = ( y,z,w,x )
shiftR(V4) V4 Shifts the vector's components right: shiftR( x,y,z,w ) = ( w,x,y,z )

Common Vector CommandsПравить

Functions that apply to 2D and 3D vectors. They are written here in terms of 3D vectors, but apply to 2D and 4D vectors in the same way, also returning 2D or 4D vectors where applicable.

Function Returns Description
ceil(V) V Rounds XYZ up to the nearest integer
ceil(V,N.png) V Rounds XYZ up to argument 2's decimal precision
floor(V) V Rounds XYZ down to the nearest integer
floor(V,N.png) V Rounds XYZ down to argument 2's decimal precision
round(V) V Rounds XYZ to the nearest integer
round(V,N.png) V Rounds XYZ to argument 2's decimal precision
mod(V,N.png) V Returns the remainder after XYZ have been divided by argument 2
mod(V,V) V Returns the remainder after the components of vector 1 have been divided by the components of vector 2
clamp(V,V,V) V Clamps vector 1's XYZ between the XYZ of vector 2(min) and vector 3(max)
clamp(V,N.png,N.png) V Clamps vector 1's length between argument 2(min) and argument 3(max)
min(V,V) V Returns the vector with the smallest length
max(V,V) V Returns the vector with the greatest length
mix(V,V,N.png) V Combines vector 1's XYZ with vector 2's XYZ by a proportion given by argument 3 (between 0 and 1)
positive(V) V Returns a vector containing the positive value of each vector component, equivalent to abs(N.png)
V:length() N.png Gets the length of the vector
V:length2() N.png Gets the squared length of the vector
V:distance(V) N.png Gets the distance between vectors
V:distance2(V) N.png Gets the squared distance between vectors
V:normalized() V Gets the normalized vector
V:dot(V) N.png Gets the vector dot (scalar) product
V:x() N.png Gets the x component of the vector
V:y() N.png Gets the y component of the vector
V:z() N.png Gets the z component of the vector
V:w() N.png Gets the w component of the vector
V:setX(N.png) V Returns a copy of the vector with X replaced (use as Vec = Vec:setX(...))
V:setY(N.png) V Returns a copy of the vector with Y replaced (use as Vec = Vec:setY(...))
V:setZ(N.png) V Returns a copy of the vector with Z replaced (use as Vec = Vec:setZ(...))
V:setW(N.png) V Returns a copy of the vector with W replaced (use as Vec = Vec:setW(...))
V:toString() S Gets the vector nicely formatted as a string "[X,Y,Z]"

MatrixПравить

Developed by: Jimlad

DescriptionПравить

2x2, 3x3 and 4x4 matrices are now supported in Expression 2. These are for more advanced manipulations involving vectors and numbers. As with vectors, for those with the relevant knowledge these can be very useful tools.

Basic operations supported:

  • Matrix addition and subtraction
  • Multiplication by scalars, vectors and matrices
  • Division by a scalar
  • Exponentiation (only integers between -1 and 2)
  • Delta of a matrix (returns a matrix)

NOTES:

Similarly to vectors, 3x3 matrix commands are referred to using "matrix", whereas 2x2 and 4x4 matrix commands use "matrix2" and "matrix4"

The "set" and "swap" functions are like the 3D vector "set" functions; they do not affect the original matrix.

Remember that operations will only work on vectors/matrices of a similar size. You cannot, for example, multiply a 3x3 matrix by a 2D vector. Also, all vectors are treated as column vectors for the purposes of matrices, so M*V will return a vector but V*M is undefined.

2x2 Matrix CommandsПравить

Functions specific to 2x2 matrices

Function Returns Description
identity2() M2 Creates a 2x2 identity matrix
matrix2() M2 Creates a 2x2 zero matrix
matrix2(N.png,N.png,N.png,N.png) M2 Creates a matrix with values in order (i.j) of: (1,1), (1,2), (2,1), (2,2)
matrix2(V2,V2) M2 Creates a matrix with vectors by columns
matrix2(M) M2 Converts a 3x3 matrix into a 2x2 matrix - all (i,3) and (3,j) are omitted
matrix2(M4) M2 Converts a 4x4 matrix into a 2x2 matrix - all (i,3), (i,4), (3,j) and (4,j) are omitted
M2:swapRows() M2 Swaps rows
M2:swapColumns() M2 Swaps columns
M2:setRow(N.png,N.png,N.png) M2 Sets the values of a row. The first argument given specifies the row(j), the following arguments are the values 1j, 2j
M2:setRow(N.png,V2) M2 Sets the values of a row. The first argument given specifies the row, the vector contains the values to set
M2:setColumn(N.png,N.png,N.png) M2 Sets the values of a column. The first argument given specifies the column(i), the following arguments are the values i1, i2
M2:setColumn(N.png,V2) M2 Sets the values of a column. The first argument given specifies the column, the vector contains the values to set

3x3 Matrix CommandsПравить

Functions specific to 3x3 matrices

Function Returns Description
identity() M Creates a 3x3 identity matrix
matrix() M Creates a 3x3 zero matrix
matrix(N.png1,N.png2... N.png9) M Creates a matrix with 9 values in the following order (i.j): (1,1), (1,2), (1,3), (2,1) etc.
matrix(V,V,V) M Creates a matrix with vectors by columns
matrix(M2) M Converts a 2x2 matrix into a 3x3 matrix - all (i,3) and (3,j) are filled with 0's
matrix(M4) M Converts a 4x4 matrix into a 3x3 matrix - all (i,4) and (4,j) are omitted
M:swapRows(N.png,N.png) M Swaps the two rows specified
M:swapColumns(N.png,N.png) M Swaps the two columns specified
M:setRow(N.png,N.png,N.png,N.png) M Sets the values of a row. The first argument given specifies the row(j), the following arguments are the values 1j, 2j, 3j
M:setRow(N.png,V) M Sets the values of a row. The first argument given specifies the row, the vector contains the values to set
M:setColumn(N.png,N.png,N.png,N.png) M Sets the values of a column. The first argument given specifies the column(i), the following arguments are the values i1, i2, i3
M:setColumn(N.png,V) M Sets the values of a column. The first argument given specifies the column, the vector contains the values to set
M:setDiagonal(N.png,N.png,N.png) M Sets the elements of the leading diagonal
M:setDiagonal(V) M Sets the elements of the leading diagonal from the components of a vector
matrix(E) M Creates a reference frame matrix from an entity's local direction vectors by columns in the order ( x, y, z )
matrix(A) M Returns a 3x3 reference frame matrix as described by the angle A. Multiplying by this matrix will be the same as rotating by the given angle.
M:x() V Returns the local x direction vector from a 3x3 coordinate reference frame matrix ( same as M:column(1) )
M:y() V Returns the local y direction vector from a 3x3 coordinate reference frame matrix ( same as M:column(2) )
M:z() V Returns the local z direction vector from a 3x3 coordinate reference frame matrix ( same as M:column(3) )
mRotation(V,N.png) M Creates a 3x3 rotation matrix, where the vector is the axis of rotation, and the number is the angle (anti-clockwise) in degrees. Example*: to rotate a vector (7,8,9) by 50 degrees about the axis (1,1,0), you would write V = mRotation(vec(1,1,0), 50) * vec(7,8,9)

* If you want to create a rotation matrix about the axes (1,0,0), (0,1,0) or (0,0,1), either use the V:rotate function, or construct a standard rotation matrix.

4x4 Matrix CommandsПравить

Functions specific to 4x4 matrices

Function Returns Description
identity4() M4 Creates a 4x4 identity matrix
matrix4() M4 Creates a 4x4 zero matrix
matrix4(N.png1,N.png2... N.png16) M4 Creates a matrix with 16 values in the following order (i.j): (1,1), (1,2), (1,3), (1,4), (2,1) etc.
matrix4(V4,V4,V4,V4) M4 Creates a matrix with vectors by columns
matrix4(M2) M4 Converts a 2x2 matrix into a 4x4 matrix - all (i,3), (i,4), (3,j) and (4,j) are filled with 0's
matrix4(M2,M2,M2,M2) M4 Constructs a 4x4 matrix from four 2x2 matrices
matrix4(M) M4 Converts a 3x3 matrix into a 4x4 matrix - all (i,4) and (4,j) are filled with 0's
M4:swapRows(N.png,N.png) M4 Swaps the two rows specified
M4:swapColumns(N.png,N.png) M4 Swaps the two columns specified
M4:setRow(N.png,N.png,N.png,N.png,N.png) M4 Sets the values of a row. The first argument given specifies the row(j), the following arguments are the values 1j, 2j, 3j, 4j
M4:setRow(N.png,V4) M4 Sets the values of a row. The first argument given specifies the row, the vector contains the values to set
M4:setColumn(N.png,N.png,N.png,N.png,N.png) M4 Sets the values of a column. The first argument given specifies the column(i), the following arguments are the values i1, i2, i3, i4
M4:setColumn(N.png,V4) M4 Sets the values of a column. The first argument given specifies the column, the vector contains the values to set
M4:setDiagonal(N.png,N.png,N.png,N.png) M4 Sets the elements of the leading diagonal
M4:setDiagonal(V4) M4 Sets the elements of the leading diagonal from the components of a vector
matrix4(E) M4 Creates a 4x4 reference frame matrix from an entity's local direction vectors by columns in the order (x, y, z, pos), with the bottom row (0,0,0,1)
matrix4(A) M4 Returns a 4x4 reference frame matrix as described by the angle A. Multiplying by this matrix will be the same as rotating by the given angle.
matrix4(A,V) M4 Returns a 4x4 reference frame matrix as described by the angle A and the position V. Multiplying by this matrix will be the same as rotating by the given angle and offsetting by the given vector.
M4:x() V Returns the local x direction vector from a 4x4 coordinate reference frame matrix ( same as M:column(1) )
M4:y() V Returns the local y direction vector from a 4x4 coordinate reference frame matrix ( same as M:column(2) )
M4:z() V Returns the local z direction vector from a 4x4 coordinate reference frame matrix ( same as M:column(3) )
M4:pos() V Returns the position vector from a 4x4 coordinate reference frame matrix ( same as M:column(4) )
inverseA(M4) M4 Finds the matrix inverse of a standard 4x4 affine transformation matrix ( the type created by matrix4(E) ). This should only be used on matrices with a particular format, where the top left 3x3 specifies rotation, the rightmost 3-column specifies translation, and the bottom row is (0,0,0,1)

Стандартные команды для матрицПравить

Функции, которые работают для матриц 2x2, 3x3 and 4x4. В данном случае написано для матриц 3*3, но применимы для матриц 2х2 и 4х4.

Операции возвращают вектора/матрицы того же размера. Например, функция row() возвращает 2D вектор.

Функция Возвращает Описание
M:row(N.png) V Возвращает строку, как вектор
M:column(N.png) V Возвращает столбец, как вектор
M:element(N.png,N.png) N.png Возвращает элемент с индексами(i,j)
M:setElement(N.png,N.png,N.png) M Устанавливает значение элемента. Первые 2 аргумента - индексы (i,j), третий элемент - значение, которое надо вставить.
M:swapElements(N.png,N.png,N.png,N.png) M Меняет 2 элемента местами ( i1, j1, i2, j2 )
diagonal(M) V Returns a vector comprising the elements along the leading diagonal
trace(M) N.png Returns the trace of a matrix
det(M) N.png Returns the determinant of a matrix (Does not work for 4x4 matrices)
transpose(M) M Returns the transpose of a matrix
adj(M) M Returns the adjugate of a matrix (Does not work for 4x4 matrices)

NOTE: To get the inverse of a matrix, simply raise the matrix to the power of -1. Use this sparingly as it can be computationally expensive! Remember that if your matrix is orthogonal (e.g. rotation matrices), the inverse is equal to the transpose, so use the transpose instead if you can. Inverse is not available for 4x4 matrices. Instead, see usage of the inverseA(M4) function.

AngleПравить

DescriptionПравить

Like 3 different directions can be expressed as a Vector, the angles of Pitch, Yaw and Roll can be expressed as an angle Vector. This in the least has the advantage that when performing functions which use angles, such as vector rotation or creating vectors from angles, you don't have to write the Pitch, Yaw and Roll components, only the Angle.

CommandsПравить

Function Returns Description
ang(N.png,N.png,N.png) A Makes an angle
ang() A Same as ang(0,0,0)
ang(V) A Changes a vector variable into an angle variable
ceil(A) A Rounds PYR up to the nearest integer
ceil(A,N.png) A Rounds PYR up to argument 2's decimal precision
floor(A) A Rounds PYR down to the nearest integer
floor(A,N.png) A Rounds PYR down to argument 2's decimal precision
round(A) A Rounds PYR to the nearest integer
round(A,N.png) A Rounds PYR to argument 2's decimal precision
mod(A,N.png) A Returns the remainder after PYR have been divided by argument 2
mod(A,A) A Returns the remainder after the components of angle 1 have been divided by the components of angle 2
clamp(A,A,A) A Clamps angle 1's PYR between the PYR of angle 2(min) and angle 3(max)
clamp(A,N.png,N.png) A Clamps angle 1's PYR between argument 2(min) and argument 3(max)
mix(A,A,N.png) A Combines angle 1's PYR with angle 2's PYR by a proportion given by argument 3 (between 0 and 1)
shiftL(A) A Shifts the angle's components left: shiftL( p,y,r ) = ( y,r,p )
shiftR(A) A Shifts the angle's components right: shiftR( p,y,r ) = ( r,p,y )
angnorm(A) A Gets the normalized angle of an angle
angnorm(N.png) N.png Gets the normalized angle of a number
A:pitch() N.png Gets the pitch of the angle
A:yaw() N.png Gets the yaw of the angle
A:roll() N.png Gets the roll of the angle
A:setPitch(N.png) A Returns a copy of the angle with Pitch replaced (use as Ang = Ang:setPitch(...))
A:setYaw(N.png) A Returns a copy of the angle with Yaw replaced (use as Ang = Ang:setYaw(...))
A:setRoll(N.png) A Returns a copy of the angle with Roll replaced (use as Ang = Ang:setRoll(...))
A:toString() S Gets the angle nicely formatted as a string "[P,Y,R]"
A:toVector() V Removed in r1340. Use vec(A) instead.
A:forward() V Gets the forward vector of the angle.
A:right() V Gets the right vector of the angle.
A:up() V Gets the up vector of the angle.

TableПравить

DescriptionПравить

Tables are a way to create dynamic variables, store large numbers of data points and so on. It may be thought of as a list of data, where each bit of data is addressed with an index string. This is a string which is unique to each element of a datatype (a number element and a vector element may have identical indices without problems, but two number elements cannot). Tables can contain any datatype except table and array.

Assigning one table variable to equal another will make them both refer to the same table. If you want to make a new copy of a table which will thereafter be set and retrieved from independently of the original table, you must use clone().

Related ExamplesПравить

CommandsПравить

In the interest of brevity, some commands which have many variants are shown as a pattern. <type> may be substituted with the capitalized name of any supported datatype, and * is the corresponding datatype symbol. For instance, R:push<type>(*) can mean R:pushNumber(N.png), or R:pushString(S).

Function Returns Description
table() T Creates an empty table
T:clone() T Creates an independent copy of a table
T:count() N.png Returns the number of used indexes in the table
invert(R) T Returns a lookup table for R. Usage: Index = T:number(toString(Value))
Don't overuse this function, as it can become expensive for arrays with > 20 entries!
invert(T) T Returns a lookup table for T. Usage: Key = T:string(toString(Value))
Don't overuse this function, as it can become expensive for tables with > 10 entries!
T:<type>(S) N.png Retrieves the requested datatype element from the indexed string. Returns the default value for the datatype if the index is nil.
T:set<type>(S,*) Saves the value as a table element with the specified index string

ArrayПравить

Thanks to: Erkle

DescriptionПравить

Same as table, but with much less memory footprint and is numerically indexed instead. It is similar to E1's packet support. Arrays can contain any datatype except table and array.

Related ExamplesПравить

CommandsПравить

In the interest of brevity, some commands which have many variants are shown as a pattern. <type> may be substituted with the capitalized name of any supported datatype, and * is the corresponding datatype symbol. For instance, R:push<type>(*) can mean R:pushNumber(N.png), or R:pushString(S).

Function Returns Description
array() R Creates an empty array
R:clone() R Creates an independant copy of an array
R:count() N.png Returns the number of used indexes in the array
R:sum() N.png Adds all numbers in the array together and returns result
R:concat() S Combines all strings and returns result
R:concat(S) S Combines all strings with specified string in between and returns result
R:average() N.png Gives the average of all numbers in array
R:min() N.png Returns the smallest number in array
R:minIndex() N.png Returns the index of the smallest number in array
R:max() N.png Returns the largest number in array
R:maxIndex() N.png Returns the index of the largest number in array
R:<type>(N.png) * Retrieves the array element indexed with the number. Returns the default value for the datatype if the element is nil.
R:set<type>(N.png,*) Saves the datatype as an array element with the specified index number
R:push<type>(*) Saves the data at the end of the array
R:pop<type>() * Deletes and returns the last entry in the array. Be sure not to use popNumber() on a vector or similar, as the data may be lost
R:pop() Deletes the last entry in the array
R:unshift<type>(*) Adds the data to the beginning of the array. Will move all other entries up one address
R:shift<type>() * Deletes and returns the first element of the array, moving other entries down one address to compensate.
R:shift() Удаляет первый элемент массива; all other entries will move down one address
R:insert<type>(N.png,*) * Inserts the data into the specified index; all entries after this index will move up to compensate
R:remove<type>(N.png) * Deletes and returns the specified entry, moving subsequent entries down to compensate
R:remove(N.png) Deletes the specified entry, moving subsequent entries down to compensate

BoneПравить

Developed by: TomyLobo

DescriptionПравить

This extension gives E2 support for bone entities. A bone can be any part of any ragdoll (head, left arm, right leg, etc).
You can get a bone's position, orientation, velocity, etc, much like with regular props (although some things are missing).

Array and table functions for bones are also provided.

Related ExamplesПравить

CommandsПравить

Function Returns Description
E:bone(N.png) B ВозвращаетE's N.pngth кость
E:bones() R Returns an array containing all of E's bones. This array's first element has the index 0!
E:boneCount() N.png Возвращает количество костейЕ
nobone() B Returns an invalid bone
E:aimBone() B Возвращает ту кость, на которую смотрит игрок
B:entity() E Returns the entity B belongs to
B:index() N.png Returns B's index in the entity it belongs to. Returns -1 if the bone is invalid or an error occured
B:pos() V Возвращает позицию В
B:forward() V Returns a vector describing B's forward direction
B:right() V Returns a vector describing B's right direction
B:up() V Returns a vector describing B's up direction
B:vel() V Returns B's velocity
B:velL() V Returns B's velocity in local coordinates
B:toWorld(V) V Transforms V from local coordinates (as seen from B) to world coordinates
B:toLocal(V) V Transforms V from world coordinates to local coordinates (as seen from B)
B:angVel() A Returns B's angular velocity
B:angles() A Returns B's pitch, yaw and roll angles
B:bearing(V) N.png Returns the bearing (yaw) from B to V
B:elevation(V) N.png Returns the elevation (pitch) from B to V
B:mass() N.png Returns B's mass
B:massCenter() V Returns B's Center of Mass
B:massCenterL() V Returns B's Center of Mass in local coordinates
B:setMass(N.png) Sets B's mass (between 0.001 and 50,000)
B:inertia() V Gets the principal components of B's inertia tensor in the form vec(Ixx, Iyy, Izz)
B:applyForce(V) Applies force to B according to V's direction and magnitude
B:applyOffsetForce(V,V2) Applies force to B according to V from the location of V2
B:applyAngForce(A) Applies torque to B according to A
B:isFrozen() N.png Returns 1 if B is frozen, 0 otherwise

WirelinkПравить

DescriptionПравить

Wirelinks are an alternative to normal wires that offer a number of advantages. Any number of inputs or outputs on a component can be manipulated with one Wirelink, and you can also use it to retrieve the entity of a wirelinked component. Since all Wirelinks are capable of two-way communication, wirelinks are not clear-cut inputs or outputs. As such, to avoid ambiguity wirelinks which the expression should be able to manipulate are always declared in the @inputs of the expression. To connect this input to another component, you must use the Wirelink tool on the component to create a new output on it of the type Wirelink, then wire the input to the output as normal.

Wirelink is not yet officially supported

Related ExamplesПравить

CommandsПравить

Equal and Not Equal operators are available. XWL here means the Wirelink input.

Function Returns Description
XWL:isHiSpeed() N.png Returns true if the linked component is high-speed capable.
XWL:entity() E Returns the entity of the linked component.
XWL:hasInput(S) N.png Returns true if the linked component has an input of the specified name.
XWL:hasOutput(S) N.png Returns true if the linked component has an output of the specified name.
XWL:setNumber(S,N.png) Sets the component's input of the specified name equal to the number.
XWL:number(S) N.png Retrieves the component's output of the specified name.
XWL:setVector(S,V) Sets the component's input of the specified name equal to the vector.
XWL:vector(S) V Retrieves the component's output of the specified name.
XWL:setString(S,S) Sets the component's input of the specified name equal to the string.
XWL:string(S) S Retrieves the component's output of the specified name.
XWL:setXyz(V) Sets the X/Y/Z to the corresponding values in the vector.
XWL:xyz() V Retrieves the X/Y/Z as the corresponding values in the vector.
XWL:setEntity(S,E) Sets the component's input of the specified name equal to the entity.
XWL:entity(S) E Retrieves the component's output of the specified name.
XWL:writeCell(N.png,N.png) N.png Writes the second argument to the memory cell specified by the first argument. Returns true if successful.
XWL:readCell(N.png) N.png Returns contents of the specified memory cell.
XWL:writeString(S,N.png,N.png) A helper function for using the Wired Console Screen. The string will be written to the screen in white text on black background. The number arguments specify the starting position - X/Horizontal (0-29 recommended) and Y/vertical (0-17).
XWL:writeString(S,N.png,N.png,N.png) As above, with an extra argument for the text colour. This is in the form of a 3-digit RGB code. 0 is black, while 999 is white, 900 is pure red and so on.
XWL:writeString(S,N.png,N.png,N.png,N.png) As above, with an extra argument for background colour. 3-digit RGB again.
XWL:writeString(S,N.png,N.png,N.png,N.png,N.png) As above, with an extra argument for flashing text. 0 or 1 is recommended.


ComplexПравить

Developed by: Fizyk

DescriptionПравить

Complex numbers are an extension of real numbers to include roots of negative numbers as well.

Related ExamplesПравить

CommandsПравить

Function Returns Description
comp() C Returns complex zero
comp(N.png) C Converts a real number to complex (returns complex number with real part N.png and imaginary part 0)
comp(N.png,N.png2) C Returns N.png+N.png2*i
i() C Returns the imaginary unit i
i(N.png) C Returns <n>*i
abs(C) C Returns the absolute value of C
arg(C) C Returns the argument of C
conj(C) C Returns the conjugate of C
real(C) N.png Returns the real part of C
imag(C) N.png Returns the imaginary part of C
exp(C) C Raises Euler's constant e to the power of C
log(C) C Calculates the natural logarithm of C
log(C,C2) C Calculates the logarithm of C2 to a complex base C
log(N.png,C) C Calculates the logarithm of C to a real base N.png
log2(C) C Calculates the logarithm of C to base 2
log10(C) C Calculates the logarithm of C to base 10
sqrt(C) C Calculates the square root of C
csqrt(N.png) C Calculates the complex square root of the real number N.png
C:pow(C2) C Raises C to the power C2
sin(C) C Calculates the sine of C
cos(C) C Calculates the cosine of C
sinh(C) C Calculates the hyperbolic sine of C
cosh(C) C Calculates the hyperbolic cosine of C
toString(C) S Formats C as a string.

QuaternionПравить

Developed by: Fizyk

DescriptionПравить

Quaternions are an extension of complex numbers. Instead of a+bi, they are of form a+bi+cj+dk, where a, b, c, d are real numbers, and i, j, k are imaginary units. The imaginary units can be used as a basis in a 3D space, allowing quaternions to represent rotations.
Like on real and complex numbers, on quaternions you can perform addition, subtraction, multiplication and division. Operations that take a quaternion and a real/complex number are also supported (N+Q, Q*C, etc.). Beware: quaternion multiplication isn't commutative!
Note: Because multiplication isn't commutative with quaternions, there are two ways of dividing them. Q1/Q2 is the same as Q1*inv(Q2), the second way is inv(Q2)*Q1.
The extension also supports multiplying quaternions by vectors for the purpose of rotations. If you want to rotate vector V using quaternion Q, use this code:
V2 = vec(Q*V*inv(Q))

A short guide on quaternions can be found here: [1]

CommandsПравить

Function Returns Description
quat() Q Creates a zero quaternion
quat(N.png) Q Creates a quaternion with real part equal to N.png
quat(C) Q Creates a quaternion with real and "i" parts equal to C
quat(V) Q Converts a vector to a quaternion (returns V.x*i + V.y*j + V.z*k)
quat(N.png,N.png2,N.png3,N.png4) Q Returns N.png+N.png2i+N.png3j+N.png4k
quat(A) Q Converts A to a quaternion
quat(V,V2) Q Creates a quaternion given forward (V) and up (V2) vectors
quat(E) Q Converts angle of E to a quaternion
qi() Q Returns quaternion i
qi(N.png) Q Returns quaternion N.png*i
qj() Q Returns j
qj(N.png) Q Returns N.png*j
qk() Q Returns k
qk(N.png) Q Returns N.png*k
abs(Q) N.png Returns absolute value of Q
conj(Q) Q Returns the conjugate of Q
inv(Q) Q Returns the inverse of Q
Q:real() N.png Returns the real component of the quaternion
Q:i() N.png Returns the i component of the quaternion
Q:j() N.png Returns the j component of the quaternion
Q:k() N.png Returns the k component of the quaternion
exp(Q) Q Raises Euler's constant e to the power Q
log(Q) Q Calculates natural logarithm of Q
qMod(Q) Q Changes quaternion Q so that the represented rotation is by an angle between 0 and 180 degrees (by coder0xff)
slerp(Q,Q2,N.png) Q Performs spherical linear interpolation between Q and Q2. Returns Q for N.png=0, Q2 for N.png=1
Q:forward() V Returns vector pointing forward for Q
Q:right() V Returns vector pointing right for Q
Q:up() V Returns vector pointing up for Q
qRotation(V,N.png) Q Returns quaternion for rotation about axis V by angle N.png
qRotation(V) Q Construct a quaternion from the rotation vector V. Vector direction is axis of rotation, magnitude is angle in degress (by coder0xff)
rotationAngle(Q) N.png Returns the angle of rotation in degrees (by coder0xff)
rotationAxis(Q) V Returns the axis of rotation (by coder0xff)
rotationVector(Q) V Returns the rotation vector - rotation axis where magnitude is the angle of rotation in degress (by coder0xff)
vec(Q) V Converts Q to a vector by dropping the real component
matrix(Q) M Converts Q to a transformation matrix
Q:toAngle() A Returns angle represented by Q
toString(Q) S Formats Q as a string.

Базовые командыПравить

CoreПравить

ОписаниеПравить

...

КомандыПравить

Команда Тип возврата Описание
first() N.png Выдает 1 если Е2 был установлен или перезапущен
duped() N.png Выдает 1 если Е2 был скопирован
inputClk() N.png Returns 1 if the expression was triggered by an input
reset() Reset the expression itself as if it was just spawned, stops execution
exit() }

Self-AwareПравить

DescriptionПравить

With entity() you can use Entity-Support to get all the data from the expression-entity. With concmd() you can execute console commands. hint() allows you to display strings quickly on your screen.

Also, the chip has the ability to thrust itself. Beware of the interval you're choosing for your contraption, because of the time response. (The thrust lasts for 10ms)

Related ExamplesПравить

КоммандыПравить

Function Returns Description
entity() E Получает entity чипа
concmd(S) N.png Takes a string and executes it in console. Returns 1 if it succeeded and 0 if it failed.
The client must enable this in the console with "wire_expression2_concmd 1".
hint(S,N.png) Отображает подсказку S на N.png секунд (N.png being clamped between 0.7 and 7)
print(S) Отображает S в чате
printTable(T) Prints a table like the lua function PrintTable does, except to the chat area.
printTable(R) Prints an array like the lua function PrintTable does, except to the chat area.
applyForce(V) Applies force according to the vector given (Forces independently on each axis unlike a vector thruster)
applyOffsetForce(V,V) Applies force to the expression according to the first vector from the location of the second
selfDestruct() Уничтожает чип
selfDestructAll() Уничтожает чип и все с ним склеено
changed(*)

Checks if the value or variable was changed. Accepts any type except table and array.
It detects changes by checking whether it was called with a different parameter at the same point in the last execution.
Multiple calls to changed() in the _same_ execution are independent of each other.

Проверяет, было изменено значение или переменная. Принимает любой тип, кроме таблиц и массива. Он обнаруживает изменения, проверяя, был ли он вызван с в другой точке.Повторные вызовы changed() в том же исполнении являются независимыми друг от друга.

TimerПравить

DescriptionПравить

Timer functions are a way to trigger the expression to be run at a given time. Most interesting is the interval(N.png) function, that lets the expression be run continuously without needing triggering from inputs.

CommandsПравить

Function Returns Description
runOnTick(N.png) If set to 1, the expression will execute once every game tick
tickClk() N.png Returns 1 if the current execution was caused by "runOnTick"
curtime() N.png Returns the current time since server-start in seconds
interval(N.png) Causes the expression to execute every N.png milliseconds (minimum delay is 10 milliseconds)
timer(S,N.png) Sets a one-time timer with entered name and delay in milliseconds
stoptimer(S) Stops a timer, can stop interval with stoptimer("interval")
clk() N.png Returns 1 if the current execution was caused by the interval
clk(S) N.png Returns 1 if the current execution was caused by the inserted name

Unit ConversionПравить

DescriptionПравить

All conversions are precise so it is recommended to round the result if it is going to be displayed (round()).

Related ExamplesПравить

CommandsПравить

Function Returns Description
toUnit(S,N.png) N.png Converts default garrysmod units to specified units
fromUnit(S,N.png) N.png Converts specified units to default garrysmod units
convertUnit(S,S,N.png) N.png Converts between two units

UnitsПравить

Length Description
mm миллиметры
cm сантиметры
dm дециметры
m метры
km километры
in дюймы (default)
ft футы
yd ярды
mi мили
nmi морская миля
Speed Description
m/s метров в секунду
km/h километров в час
in/s дюймов в секунду
mi/h миль в час
mph miles per hour (more commonly used than mi/h)
knots knots (correct term for nautical miles per hour)
mach mach (times speed of sound)
mm/x millimeters per time unit
cm/x centimeters per time unit
dm/x decimeters per time unit
m/x meters per time unit
km/x kilometers per time unit
in/x inches per time unit
ft/x feet per time unit
yd/x yards per time unit
mi/x miles per time unit
nmi/x nautical miles per time unit
substitute x for s (per second), m (per minute) or h (per hour)
Weight Description
g грамм
kg килограмм
t тон
oz ounces
lb pounds

Информация Править

Developed by: Beer

ОписаниеПравить

The following functions allow you to get various information about the server, such as the current map name, gamemode, etc.

Команды Править

Функции Возвращает Описание
map() S Возвращает текущее название карты
hostname() S Возвращает название сервера
isLan() N.png Returns 1 if lan mode is enabled
gamemode() S Возвращает название текущего gamemode
gravity() N.png Возвращает гравитацию
ping() N.png Returns the latency (Player:ping() для индивидуального игрока)
isSinglePlayer() N.png Возвращает 1,если в одиночной игре, а 0, если в сетевой игре
isDedicated() N.png Returns 1 if server is dedicated, 0 if listen
numPlayers() N.png Возвращает текущее число игроков на сервере
maxPlayers() N.png Возвращает максимальное число игроков на сервере
maxOfType(S) N.png Returns the maximum allowed of a certain type of entity, i.e. maxOfType("wire_thrusters"). Returns 0 if you enter an invalid parameter.
playerDamage() N.png Возвращает 1, если ПВП урон включен на этом сервере
convar(S) S Give a console command such as "name" and it returns the set value
convarnum(S) N.png Give a console command such as "sbox_godmode" and it returns the set value
time(S) N.png Returns numerical time/date info from the server. Possible arguments: "year", "month", "day", "hour", "min", "sec", "wday" (weekday, Sunday is 1), "yday" (day of the year), and "isdst" (daylight saving flag 0/1)
  • TIP: To get a list of all possible parameters for maxOfType(), open the console and type "find sbox_max". If you need "sbox_maxragdolls", you can simply pass "ragdolls" in the function.

Constraint Править

Developed by: ZeikJT

ОписаниеПравить

The following functions get information about entities based on constraints

Команды Править

Function Returns Description
E:getConstraints() R Returns an array with all entities constrained to E.
E:hasConstraints() N.png Returns the number of the constraints E has
E:hasConstraints(S) N.png Returns the number of the constraints E has with the given constraint type (see the types list below)
E:isConstrained() N.png Returns 1 if E has constraints, 0 if not
E:isWeldedTo() E Returns the first entity E was welded to
E:isWeldedTo(N.png) E Возвращает N.pngth entity E was welded to
E:isConstrainedTo() E Returns the first entity E was constrained to
E:isConstrainedTo(N.png) E Returns the N.pngth entity E was constrained to
E:isConstrainedTo(S) E Returns the first entity E was constrained to with the given constraint type (see the types list below)
E:isConstrainedTo(S, N.png) E Returns the N.pngth entity E was constrained to with the given constraint type (see the types list below)
E:parent() E Returns the entity E is parented to.
E:parentBone() B Returns the bone E is parented to.
Constraint Types
AdvBallsocket
Axis
Ballsocket
Elastic
Hydraulic
Keepupright
Motor
Muscle
NoCollide
Pulley
Rope
Slider
Weld
Winch

Chat Править

Developed by: ZeikJT & Gwahir

Описание Править

The following functions are for reading the chat log. This is similar to the text receiver.

Related ExamplesПравить

Команды Править

Function Returns Description
runOnChat(N.png) 1 will cause the chip to run on chat events, 0 stops the chip from running on chat events, only needs to be called once (not every execution)
chatClk() N.png Returns 1 if the chip is being executed because of a chat event, 0 otherwise.
chatClk(E) N.png Returns 1 if the chip is being executed because of a chat event by the given player, 0 otherwise.
hideChat(N.png) If N.png != 0, hide the chat message that is currently being processed.
lastSaid() S Returns what the last message was in the chat log
lastSaidWhen() N.png Returns the time the last message was said
E:lastSaid() S Returns what the given player last said
E:lastSaidWhen() N.png Returns when the given player last said something
lastSpoke() E Returns the entity of the last player to speak

ColorПравить

Developed by: Jimlad

DescriptionПравить

These commands allow E2 to find the color of an entity and change it. Changing color only works on entities you own.

Uses RGBA (Red, Green, Blue, Alpha) values, although when only RGB is specified, alpha will not be changed.

Note that color values have a range of 0 - 255, where (0,0,0,255) is black, and (255,255,255,255) is white.

Alpha is equivalent to opacity, where 0 is completely transparent and 255 is completely opaque.

CommandsПравить

Function Returns Description
E:getColor() V Returns the color of an entity as a vector (R,G,B)
E:getColor4() V4 Returns the color of an entity as a 4D vector (R,G,B,A)
E:getAlpha() N.png Returns the alpha of an entity
E:getMaterial() S Returns the material of an entity
E:setColor(N.png,N.png,N.png) Changes the RGB color of an entity (leaves alpha alone)
E:setColor(N.png,N.png,N.png,N.png) Changes the RGBA color of an entity
E:setColor(V) Changes the RGB color of an entity (leaves alpha alone), using a vector with values (R,G,B)
E:setColor(V,N.png) Changes the RGBA color of an entity, using a vector with values (R,G,B). The additional argument sets alpha
E:setColor(V4) Changes the RGBA color of an entity, using a 4D vector with values (R,G,B,A)
E:setAlpha(N.png) Changes the alpha of an entity
E:setMaterial(S) Sets the material of an entity. E:setMaterial("") to reset material

Advanced extensionsПравить

Entity DiscoveryПравить

Developed by: Gwahir, TomyLobo

DescriptionПравить

Use these to find and filter entities. The basic find functions will return how many entities were found but the actual entities are stored on the chip until they are accessed using find(), findResult(N.png), or findClosest(V)

There is a white list and a black list as well as functions for on the spot filtering and sorting White and black lists are always in effect and will be used automatically when you request a new list of entities. Control of the lists is achieved through the find[Exclude, Allow, Include, Disallow][Player, Prop, Model, Class] functions Exclude/Allow add/remove items from the black list while Include/Disallow do the same for the white list If the same object is covered by both the white list and the black list, the black list takes priority

In the case of names, classes and models, partial strings are acceptable.

Discovering entities is not cheap so suggested usage is to find what you're looking for an hold onto it in order to limit the number of queries you run. To prevent overuse of these features, two console variables have been included, wire_exp2_entFindRate and wire_exp2_playerFindRate. These are delays that control how often you can perform find queries, the ent variable is per chip, the player variable is for all chip owned by a specific player

Related ExamplesПравить

CommandsПравить

Function Returns Description
findUpdateRate() N.png Returns the minimum delay between entity find events on a chip
findPlayerUpdateRate() N.png Returns the minimum delay between entity find events per player
findCanQuery() N.png Returns 1 if find functions can be used, 0 otherwise.
findInSphere(V,N.png) N.png Finds entities in a sphere around V with a radius of N.png, returns the number found after filtering
findInCone(V,V,N.png,A) N.png Like findInSphere but with a cone, arguments are for position, direction, length, and degrees (currently bugged, because the underlying function is bugged)
findInBox(V,V) N.png Like findInSphere but with a globally aligned box, the arguments are the diagonal corners of the box
findByN.pngame(S) N.png Find all entities with the given name
findByModel(S) N.png Find all entities with the given model
findByClass(S) N.png Find all entities with the given class
findPlayerByName(S) E Returns the player with the given name, this is an exception to the rule
findExcludeEntities(R) Exclude all entities from R from future finds
findExcludeEntity(E) Exclude E from future finds
findExcludePlayer(E) Exclude this player from future finds (put it on the entity blacklist)
findExcludePlayer(S) Exclude this player from future finds (put it on the entity blacklist)
findExcludePlayerProps(E) Exclude entities owned by this player from future finds
findExcludePlayerProps(S) Exclude entities owned by this player from future finds
findExcludeModel(S) Exclude entities with this model (or partial model name) from future finds
findExcludeClass(S) Exclude entities with this class (or partial class name) from future finds
findAllowEntities(R) Remove all entities from R from the blacklist
findAllowEntity(E) Remove E from the blacklist
findAllowPlayer(E) Remove this player from the entity blacklist
findAllowPlayer(S) Remove this player from the entity blacklist
findAllowPlayerProps(E) Remove entities owned by this player from the blacklist
findAllowPlayerProps(S) Remove entities owned by this player from the blacklist
findAllowModel(S) Remove entities with this model (or partial model name) from the blacklist
findAllowClass(S) Remove entities with this class (or partial class name) from the blacklist
findIncludeEntities(R) Include all entities from R in future finds, and remove others not in the whitelist
findIncludeEntity(E) Include E in future finds, and remove others not in the whitelist
findIncludePlayer(E) Include this player in future finds, and remove other entities not in the entity whitelist
findIncludePlayer(S) Include this player in future finds, and remove other entities not in the entity whitelist
findIncludePlayerProps(E) Include entities owned by this player from future finds, and remove others not in the whitelist
findIncludePlayerProps(S) Include entities owned by this player from future finds, and remove others not in the whitelist
findIncludeModel(S) Include entities with this model (or partial model name) in future finds, and remove others not in the whitelist
findIncludeClass(S) Include entities with this class (or partial class name) in future finds, and remove others not in the whitelist
findDisallowEntities(R) Remove all entities from R from the whitelist
findDisallowEntity(E) Remove E from the whitelist
findDisallowPlayer(E) Remove this player from the entity whitelist
findDisallowPlayer(S) Remove this player from the entity whitelist
findDisallowPlayerProps(E) Remove entities owned by this player from the whitelist
findDisallowPlayerProps(S) Remove entities owned by this player from the whitelist
findDisallowModel(S) Remove entities with this model (or partial model name) from the whitelist
findDisallowClass(S) Remove entities with this class (or partial class name) from the whitelist
findClearBlackList() Clear all entries from the entire blacklist
findClearBlackEntityList() Clear all entries from the entity blacklist
findClearBlackPlayerPropList() Clear all entries from the prop owner blacklist
findClearBlackModelList() Clear all entries from the model blacklist
findClearBlackClassList() Clear all entries from the class blacklist
findClearWhiteList() Clear all entries from the entire whitelist
findClearWhiteEntityList() Clear all entries from the player whitelist
findClearWhitePlayerPropList() Clear all entries from the prop owner whitelist
findClearWhiteModelList() Clear all entries from the model whitelist
findClearWhiteClassList() Clear all entries from the class whitelist
findResult(N.png) E Returns the indexed entity from the previous find event (valid parameters are 1 to the number of entities found)
findClosest(V) E Returns the closest entity to the given point from the previous find event
findToArray() R Formats the query as an array, R:entity(Index) to get a entity, R:string to get a description including the name and entity id.
find() E Equivalent to findResult(1)
findSortByDistance(V) N.png Sorts the entities from the last find event, index 1 is the closest to point V, returns the number of entities in the list
findClipToClass(S) N.png Filters the list of entities by removing all entities that are NOT of this class
findClipFromClass(S) N.png Filters the list of entities by removing all entities that are of this class
findClipToModel(S) N.png Filters the list of entities by removing all entities that do NOT have this model
findClipFromModel(S) N.png Filters the list of entities by removing all entities that do have this model
findClipToName(S) N.png Filters the list of entities by removing all entities that do NOT have this name
findClipFromName(S) N.png Filters the list of entities by removing all entities that do have this name
findClipToSphere(V,N.png) N.png Filters the list of entities by removing all entities NOT within the specified sphere (center, radius)
findClipFromSphere(V,N.png) N.png Filters the list of entities by removing all entities within the specified sphere (center, radius)
findClipToRegion(V,V2) N.png Filters the list of entities by removing all entities NOT on the positive side of the defined plane. (Plane origin, vector perpendicular to the plane) You can define any convex hull using this.

Global VariablesПравить

Developed by: ZeikJT

DescriptionПравить

Global variables are a way to exchange data between two expression chips without the need for any wiring at all.

The global variables will be sorted into groups so that you can avoid two chips overwriting each other's global data. By default a newly spawned chip will default to "default" as the group entry, but you can always change that by using the gSetGroup(s) function.

Remember, all global variables persist until you delete them or you leave the server. They will never automatically reset.

Using tables like this does isn't exactly a memory free deal, when using this on servers try to keep the amount of stored global variable at any one time down to a minimum.

As of right now the global group will be reset after every run. Also, try to keep the group setting down to a minimum as it can be costly.

Related ExamplesПравить

CommandsПравить

Function Returns Description
gSetStr(S) Stores a string into the current group, use with gGetStr(S)
gSetStr(S,S) Stores the second string into the current group under the index specified by the first string
gSetStr(N.png,S) Stores the string into the current group under the index specified by the number
gSetNum(N.png) Stores a number into the current group, use with gGetNum(N.png)
gSetNum(S,N.png) Stores the number into the current group under the index specified by the string
gSetNum(N.png,N.png) Stores the second number into the current group under the index specified by the first number
gGetStr() S Returns the string under the current group stored only by gSetStr(S)
gGetStr(S) S Returns the string under the current group stored in the input string index, use with gSetStr(S,S)
gGetStr(N.png) S Returns the string under the current group stored in the input number index, use with gSetStr(N.png,S)
gGetNum() N.png Returns the number under the current group stored only by gSetNum(N.png)
gGetNum(S) N.png Returns the number under the current group stored in the input string index, use with gSetNum(S,N.png)
gGetNum(N.png) N.png Returns the number under the current group stored in the input number index, use with gSetNum(N.png,N.png)
gDeleteStr() S Like gGetStr() but deletes the value after retrieval
gDeleteStr(S) S Like gGetStr(S) but deletes the value after retrieval
gDeleteStr(N.png) S Like gGetStr(N.png) but deletes the value after retrieval
gDeleteNum() N.png Like gGetNum() but deletes the value after retrieval
gDeleteNum(S) N.png Like gGetNum(S) but deletes the value after retrieval
gDeleteNum(N.png) N.png Like gGetNum(N.png) but deletes the value after retrieval
gSetGroup(S) Sets the group that all global write, read, and delete functions will use, default is "default"
gGetGroup() S Returns the name of the current group for the chip
gShare(N.png) Determines whether or not the group you're in is available only to you or to all players. Defaults to 0. Any value but 0 will set your group to be accessible to all players. Be mindful that there are two groups with every name, one is shared, one is not; values do not transition between the two.
gResetGroup() Returns the current chip's group back to "default"
gDeleteAllStr() Deletes all of the global strings stored under the current group, including the one stored by gSetStr(S)
gDeleteAllNum() Deletes all of the global numbers stored under the current group, including the one stored by gSetNum(N.png)
gDeleteAll() Deletes all of the global values stored under the current group, including the ones stored by gSetStr(S) and gSetNum(N.png)

Built-In RangerПравить

Developed by: ZeikJT

DescriptionПравить

The built-in ranger is heavily based on Erkle's original ranger. There are however some new functionalities that can be found in the commands below. Keep in mind that if you want to apply an option you must set it pre-ranging.

This also introduces a new Variable type, the RD (defined as :ranger). It holds the data returned after a trace, you will need to use the trace data functions to retrieve useful data. These are to be used after you have done an actual trace.

I will add a simple example to showcase the syntax and functionality.

Related ExamplesПравить

CommandsПравить

Function Returns Description
Ranger Options To be used before an actual ranger trace
rangerHitWater(N.png) Default is 0, if any other value is given it will hit water
rangerIgnoreWorld(N.png) Default is 0, if any other value is given it will ignore world
rangerDefaultZero(N.png) If given any value other than 0 it will default the distance data to zero when nothing is hit
rangerFilter(E) Feed entities you don't want the trace to hit
rangerFilter(R) Feed an array of entities you don't want the trace to hit
Ranger Tracing Gathers data, if options are declared prior to this they will be used
ranger(N.png) RD You input max range, it returns ranger data
ranger(N.png,N.png,N.png) RD Same as above with added inputs for X and Y skew
rangerAngle(N.png,N.png,N.png) RD You input the distance, x-angle and y-angle (both in degrees) it returns ranger data
rangerOffset(V,V) RD You input two vector points, it returns ranger data
rangerOffset(N.png,V,V) RD You input the range, a position vector, and a direction vector and it returns ranger data
Ranger Data Retreval Accesses data stored in an RD container
RD:distance() N.png Outputs the distance from the rangerdata input, else depends on rangerDefault
RD:position() V Outputs the position of the input ranger data trace IF it hit anything, else returns (0,0,0)
RD:entity() E Returns the entity of the input ranger data trace IF it hit an entity, else returns nil
RD:hit() N.png Returns 1 if the input ranger data hit anything and 0 if it didn't
RD:hitNormal() V Outputs a normalized vector perpendicular to the surface the ranger is pointed at.

Sound PlaybackПравить

Developed by: ZeikJT

DescriptionПравить

Allows Expression 2 to play sounds. You can find a list of Half-life 2 sounds here or use GCFScape to preview each sound.

The Duration is in seconds. If the sound is meant to be looped, set the duration to zero. If a sound is not designed to be looped (i.e: actor talking), it won't loop. The path must contain slashes '/' and not backslashes '\'.

CommandsПравить

Function Returns Description
soundPlay(N.png,N.png,S) soundPlay(int Index, int Duration, string Path to File)
soundPlay(S,N.png,S) soundPlay(string Index, int Duration, string Path to File)
soundPlay(N.png,N.png,S,N.png) soundPlay(int Index, int Duration, string Path to File, int FadeTime)
soundPlay(S,N.png,S,N.png) soundPlay(string Index, int Duration, string Path to File, int FadeTime)
soundStop(N.png) Stops the sound stored at the integer index and removes the entry
soundStop(N.png,N.png) Fades the sound stored at the first input's integer index in the second input's amount of seconds and removes the entry
soundStop(S) Stops the sound stored at the string index and removes the entry
soundStop(S,N.png) Fades the sound stored at the string index in the integer input's amount of seconds and removes the entry
soundPitch(N.png,N.png) soundPitch(integer Index, integer Pitch) (default Pitch is 100)
soundPitch(S,N.png) Same as above but takes a string index instead of an integer index
soundVolume(N.png,N.png) soundVolume(integer Index, integer Volume) (default Volume is 1)
soundVolume(S,N.png) Same as above but takes a string index instead of an integer index
soundPurge() Clears the sound table and stops all sounds

NPC controlПравить

Developed by: Bobsymalone

DescriptionПравить

These functions allow you to control NPCs. You can create secondary AI systems responding to wire by telling NPCs how to feel about certain things, where to go, etc. You can also equip them with weapons.

Related ExamplesПравить


CommandsПравить

Function Returns Description
E:npcStop() Прекращает любое действие НПС
E:npcGoWalk(V) Командует НПС идти на позицию V
E:npcGoRun(V) Командует НПС бежать на позицию V
E:npcFace(V) This will rotate the NPC to face position V. This is purely aesthetic and can't be used to aim their weapon.
E:npcAttack() Командует НПС бить
E:npcShoot() Командует НПС стрелять
E:npcGiveWeapon() Выдает НПС пулемет (SMG)
E:npcGiveWeapon(S) Выдает НПС оружие. Например: E:npcGiveWeapon("pistol"). Другие варианты оружия: "ar2", "crowbar", "357", "shotgun", "crossbow", "rpg", "frag", etc.
E:npcRelationship(E,S,N.png) Will set the NPC's relationship to the specified entity to the S input, priority N. Priority is any number between 0 and 999. The relationship string can be either "like" "neutral" "hate" or "fear". Same goes for all other relationship functions.
E:npcRelationship(S,S,N.png) Same as above, but sets relationship to an entire class specified by the first string. Example: "npc_manhack", "prop_physics".
E:npcRelationshipByOwner(E,S,N.png) N.png Sets the NPC's relationship to all currently existing NPCs owned by player E. Returns number of entities added to relationships.
E:npcDisp(E) S Returns the NPC's relationship to entity E.

SignalsПравить

Developed by: Gwahir, TomyLobo

DescriptionПравить

These functions allow you to remotely execute exp2 chips, provided that chip is set to receive the given signal


ScopeПравить

Signals are restricted to certain scopes (only you, anyone, only others) (0,1,2)

Simplified, true = anyone, false = only you.

Scopes are used to restrict both who can receive your signal and who's signal you can receive.

Scopes are always relative to the owner of the chip. So if player A sends to scope 1 and player B only receives from scope 0, he/she won't receive it, but player B will receive it with scopes 1 or 2


GroupПравить

Set the chip's group with signalSetGroup(S) before calling the related runOnSignal, sendSignal, or signalSetOnRemove function

The chip's signal group is always "default" at the start of every execution.

runOnSignal() will subscribe to the given signal within the current group, this applies to sent signals as well.

Any signal the chip receives will run the chip regardless of its current group (so long as it subscribed to the signal and group of the sent signal)


A chip will never run because of a signal it sent itself.

Signals are issued 10ms after the first unissued signal was sent.
There can only ever be one unissued signal/group combination per receiver in each scope.

Related ExamplesПравить

CommandsПравить

Function Returns Description
signalSetGroup(S) Sets the E-2's current signal group to S, this is applied during runOnSignal, signalSend, and signalSetOnRemove calls, so call it first.
signalGetGroup() S Gets the E-2's current signal group
runOnSignal(S,N.png,N.png2) If N.png2 == 0 the chip will no longer run on this signal, otherwise it makes this chip execute when signal S is sent by someone in scope N.png.
signalClk() N.png Returns 1 if the chip was executed because of any signal, regardless of name, group or scope. Returns 0 otherwise.
signalClk(S) N.png Returns 1 if the chip was executed because the signal S was sent, regardless of group or scope. Returns 0 otherwise.
signalClk(S,N.png) N.png Returns 1 if the chip was executed because the signal S was sent to the scope N.png, regardless of group. Returns 0 otherwise.
signalClk(S,S2) N.png Returns 1 if the chip was executed because the signal S2 was sent in the group S, regardless of scope. Returns 0 otherwise.
signalClk(S,S2,N.png) N.png Returns 1 if the chip was executed because the signal S2 was sent in the group S to the scope N.png. Returns 0 otherwise.
signalName() S Returns the name of the received signal.
signalGroup() S Returns the group name of the received signal.
signalSender() E Returns the entity of the chip that sent the signal.
signalSenderId() N.png Returns the entity ID of the chip that sent the signal. Useful if the entity doesn't exist anymore.
signalSetOnRemove(S,N.png) Sets the signal that the chip sends when it is removed from the world.
signalClearOnRemove() Clears the signal that the chip sends when it is removed from the world.
signalSend(S,N.png) Sends signal S to scope N. Additional calls to this function with the same signal will overwrite the old call until the signal is issued.
signalSendDirect(S,E) Sends signal S to the given chip. Multiple calls for different chips do not overwrite each other.
signalSendToPlayer(S,E) sends signal S to chips owned by the given player, multiple calls for different players do not overwrite each other


GLONПравить

Developed by: TomyLobo

DescriptionПравить

This extension allows you to serialize (=turn into a string) an array or table of values. Unsupported element types are:

  • Bone
  • some entity types (Vehicle, NPC, Weapon)
  • ranger data if the ranger was pointed at one of the entity types mentioned previously.

Related ExamplesПравить

CommandsПравить

Function Returns Description
glonEncode(R) S Encodes R into a string, using GLON.
glonEncode(T) S Encodes T into a string, using GLON.
glonDecode(S) R Decodes S into an array, using GLON.
glonDecodeTable(S) T Decodes S into a table, using GLON.

3D HologramsПравить

Developed by: IamMcLovin & ZeikJT

DescriptionПравить

Adds the ability to project 3D objects. These objects can't be interacted with like most props; the only way to manipulate them is to use these functions.

When using the holoCreate function, bear in mind that there is a delay associated with spawning holograms to avoid lagging servers. Avoid using holoCreate every execution. In general you should only ever use the holoCreate function once for each hologram in your code, for example by using the first() condition. Use the other functions like holoPos to update them thereafter.

Note that except for wire_holograms_display_owners, все другие консольные коммнды are useable by admins only!

Console VariablesПравить

Function Returns Description
wire_holograms_display_owners Показывает лист владельцов галограмм
wire_holograms_remove_all Removes all holograms on the map
wire_holograms_block Input a name (or part of a name) to prevent a player from spawning holograms
wire_holograms_unblock Input a name (or part of a name) to allow a player to spawn holograms again
wire_holograms_block_id Input a SteamID to prevent a player from spawning holograms
wire_holograms_unblock_id Input a SteamID to allow a player to spawn holograms again
wire_holograms_max Defines the maximum number of hologams a player can have at once
wire_holograms_size_max Defines the maximum size of holograms according to the holoScale function

Related ExamplesПравить

CommandsПравить

Function Returns Description
holoCreate(N.png,V,V,A,V) Index, Position, Scale, Angle, Color (RGB)
Создать голограмму
holoCreate(N.png,V,V,A) Index, Position, Scale, Angle
Создать голограмму
holoCreate(N.png,V,V) Index, Position, Scale
Создать голограмму
holoCreate(N.png,V) Index, Position
Создать голограмму
holoCreate(N.png) Index
Создать голограмму
holoDelete(N.png) Index
Removes the hologram with the specified index
holoScale(N.png,V) Index, Scale
Размер голограммы
holoScaleUnits(N.png,V) Index, Scale
Scales a hologram in each direction according to Garry's Mod units, given by a vector
holoPos(N.png,V) Index, Position
Установить позицию голограммы
holoColor(N.png,V,N.png) Index, Color, Alpha
Изменить цвет голограммы
holoColor(N.png,V) Index, Color
Изменить цвет голограммы
holoAlpha(N.png,N.png) Index, Alpha
Changes the alpha of a hologram
holoShadow(N.png,N.png) Index, Shadow
Установив это значение в 0 у голограммы отключаються все тени, установка значения в 1 приведёт к их отображению
holoAng(N.png,A) Index, Angle
Установить позицию вращения голограммы
holoModel(N.png,S,N.png) Index, Model, Skin
Установить модель на голограмму
holoModel(N.png,S) Index, Model
Установить модель на голограмму
holoSkin(N.png,N.png) Index, Skin
Смена скина голограммы
holoMaterial(N.png,S) Index, Material
Смена материала голограммы
holoRenderFX(N.png,N.png) Index, Render FX #
Changes the RenderFX for a hologram
holoParent(N.png,N.png) Index (current Holo), Index (Holo being parented to)
Attaches a hologram to another hologram
holoParent(N.png,E) Index, Entity
Закрепить голограмму за ентитей
holoUnparent(N.png) Index
Removes any parenting associations from a hologram
Model List
["cone"]
["cube"]
["cylinder"]
["icosphere"]
["icosphere2"]
["icosphere3"]
["prism"]
["pyramid"]
["sphere"]
["sphere2"]
["sphere3"]
["torus"]
["torus2"]
["torus3"]

ПримерыПравить

Если вы сделаете свой гайд по E2, пожалуйста добавьте его в этот список! Не забывайте про обмен(оставляйте там ссылочку на эту вики)

See AlsoПравить

CreditsПравить

I would like to extend thanks to all of the following people who have made contributions to Expression 2 in one way or another, making it into what it is today.

Shandolum, ZeikJT, Jimlad, Beer, Magos Mechanicus, Gwahir, chinoto, pl0x, Turck3, Ph3wl, Hunter234564, Fishface60, GUN, Bobsymalone, TomyLobo, Tolyzor, Jeremydeath, I am McLovin, Fizyk, Divran, Rusketh

And of course all you others out there who use it, provide constructive feedback or help others become familiar with it!

Thank you! // Syranide

P.S. I'm sorry if I forgot to mention someone!

Викия-сеть

Случайная вики