ACSUtils Wiki

An ACS library for ZDoom-based ports

User Tools

Site Tools


ru:math

This is an old revision of the document!


Математика

Заметки

Что такое "num"?

num означает “любой численный тип” (int или fixed). Функции, принимающие num, принимают и int, и fixed. Например:

num max(num a, num b)

означает:

“Функция max принимает два числа и возвращает число. Если оба аргумента – int, то она возвращает int. Если же оба аргумента fixed, то она возвращает fixed”.

Это позволяет использовать функцию max обоими способами:

max(2, 5) == 5
max(2.0, 5.0) == 5.0

Не смешивайте int и fixed числа в num. num в сигнатуре функции все являются либо int, либо fixed! Например, вот так неправильно:

max(5, 2.0)

Функция вернёт 2.0, потому что 2.0 (65536) больше, чем 5.

Об углах

Все углы в ACSUtils используют формат fixed-point angles из ZDoom (обороты), и допускается их выход за пределы диапазона 0.0-1.0. Все подобные случаи правильно обрабатываются и движком, и ACSUtils.

Константы

ACSUtils предоставляет набор математических констант. Все fixed констаты имеют много цифр после запятой, чтобы максимизировать точность. Они имеют даже больше цифр после запятой, чем нужно.

Пи и Тау

  • fixed PI = 3.1415926535897932384626433832795;
  • fixed TAU = 6.2831853071795864769252867665590;

Числа Пи и Тау.

e

fixed MATH_E = 2.7182818284590452353602874713526624977572470937;

Число e. Названо MATH_E во избежание конфликтов с именем переменной e.

Важные квадратные корни и логарифмы

Предварительно рассчитаны с максимальной точностью и часто встречаются в некоторых алгоритмах.

  • fixed SQRT_2 = 1.41421356237; – sqrt(2)
  • fixed LOG2_E = 1.44269504089; – log2(e)
  • fixed LOG2_10 = 3.32192809489; – log2(10)

Математические функции общего назначения

abs

num abs(num x)

Возвращает модуль X:

  • Если X – ноль или положительное число, возвращает X.
  • Если X – отрицательное число, возвращает -X.
Остерегайтесь использования этой функции с INT_MIN.

abs(INT_MIN) == INT_MIN, потому что -INT_MIN == INT_MIN. Это единственный случай, когда abs возвращает отрицательное число.

sgn

int sgn(int x)

Возвращает знак X:

  • Если X положителен, возвращает 1.
  • Если X отрицателен, возвращает -1.
  • Если X – ноль, возвращает 0.

Пример использования

// Задаём скорость по X равную 15.0
// но с таким же знаком, что и у foo
int xvel = sgn(foo) * 15.0;

min

num min(num a, num b)

Возвращает меньшее из двух чисел.

max

num max(num a, num b)

Возвращает большее из двух чисел.

clamp

num clamp(num x, num минимум, num максимум)

Ограничивает X в указанном диапазоне:

  • Если X меньше минимума, возвращает минимум.
  • Если X между минимумом и максимумом, возвращает X.
  • Если X больше максимума, возвращает максимум.

cmp

int cmp(num a, num b)

Compares two numbers and returns the result:

  • If A > B, returns 1.
  • If A = B, returns 0.
  • If A < B, returns -1.

Trigonometry

ACSUtils provides a full set of trigonometric functions:

  • sin is already built into ZDoom.
  • cos is already built into ZDoom.
  • fixed tan(fixed angle) – implemented as FixedDiv(sin(x), cos(x)).
  • fixed cot(fixed angle) – implemented as FixedDiv(cos(x), sin(x)).
  • fixed sec(fixed angle) – implemented as FixedDiv(1.0, sin(x)).
  • fixed cosec(fixed angle) – implemented as FixedDiv(1.0, cos(x)).

Inverse trigonometric functions:

  • fixed atan(fixed x) – implemented as VectorAngle(1.0, x).
  • fixed acot(fixed x) – implemented as 0.25 - atan(x).
  • fixed asin(fixed x) – implemented as atan(FixedDiv(x, FixedSqrt(1.0 - FixedMul(x, x)))).
  • fixed acos(fixed x) – implemented as ang(2 * atan(FixedSqrt(FixedDiv(1.0 - x, 1.0 + x)))).
  • fixed asec(fixed x) – implemented as acos(FixedDiv(1.0, x)).
  • fixed acosec(fixed x) – implemented as asin(FixedDiv(1.0, x)).

Vector math

VectorLength3D

fixed VectorLength3D(fixed x, fixed y, fixed z)

A 3D version of VectorLength. Returns the length of the 3D vector.

dot

  • 2D: fixed dot2(fixed x1, fixed y1, fixed x2, fixed y2)
  • 3D: fixed dot3(fixed x1, fixed y1, fixed z1, fixed x2, fixed y2, fixed z2)

Returns the dot product of two vectors. Shorthand for writing out FixedMul(x1, x2) + FixedMul(y1, y2) + ….

normalize

  • 2D: fixed, fixed normalize2d(fixed x, fixed y)
  • 3D: fixed, fixed, fixed normalize3d(fixed x, fixed y, fixed z)

Normalizes the vector and returns the result using multiple return values.

Example usage

normalize3d(x, y, z);
x = r1;
y = r2;
z = r2;
normalize2d(x, y);
int normalizedX = r1;
int normalziedY = r2;

RotateVector

fixed, fixed RotateVector(fixed x, fixed y, fixed angle)

Rotates the vector by the angle and returns the result using multiple return values.

Example usage

RotateVector(x, y, angle);
x = r1;
y = r2;

RotateVectorCS

fixed, fixed RotateVector(fixed x, fixed y, fixed cos, fixed sin)

A faster version of RotateVector that accepts cos(angle) and sin(angle) instead of computing them.

RotatePoint

fixed, fixed RotatePoint(fixed x, fixed y, fixed originX, fixed originY, fixed angle)

Rotates the point around the specified origin by the angle and returns the result using multiple return values.

SqVectorLength

  • fixed SqVectorLength(fixed x, fixed y)
  • fixed SqVectorLength3D(fixed x, fixed y, fixed z)

Returns vector length squared.

Because this function returns a fixed, it won't work correctly for vectors longer than 256.0!

VectorToAngles

fixed, fixed VectorToAngles(fixed x, fixed y, fixed z

Converts the vector to a pair of angles (angle, pitch) and returns them using multiple return values.

Example usage

// This function makes the actor look in the direction
// specified as a 3D vector.
function void LookInDirection(int tid, int x, int y, int z)
{
    VectorToAngles(x, y, z);
    int angle = r1;
    int pitch = r2;
    SetActorAngle(tid, angle);
    SetActorPitch(tid, -pitch); // SetActorPitch expects inverted pitch.
}

AnglesToVector

fixed, fixed, fixed AnglesToVector(fixed angle, fixed pitch)

Converts a pair of angles (angle, pitch) to a 3D vector of length 1.0 and returns it using multiple return values.

ru/math.1555619216.txt.gz · Last modified: 2019/04/18 23:26 by korshun