This page has been translated automatically.
Видеоуроки
Интерфейс
Основы
Продвинутый уровень
Подсказки и советы
Основы
Программирование на C#
Рендеринг
Профессиональный уровень (SIM)
Принципы работы
Свойства (properties)
Компонентная Система
Рендер
Физика
Редактор UnigineEditor
Обзор интерфейса
Работа с ассетами
Контроль версий
Настройки и предпочтения
Работа с проектами
Настройка параметров ноды
Setting Up Materials
Настройка свойств
Освещение
Sandworm
Использование инструментов редактора для конкретных задач
Расширение функционала редактора
Встроенные объекты
Ноды (Nodes)
Объекты (Objects)
Эффекты
Декали
Источники света
Geodetics
World-ноды
Звуковые объекты
Объекты поиска пути
Player-ноды
Программирование
Основы
Настройка среды разработки
Примеры использования
C++
C#
UnigineScript
Плагины
Форматы файлов
Материалы и шейдеры
Rebuilding the Engine Tools
Интерфейс пользователя (GUI)
Двойная точность координат
API
Animations-Related Classes
Containers
Common Functionality
Controls-Related Classes
Engine-Related Classes
Filesystem Functionality
GUI-Related Classes
Math Functionality
Node-Related Classes
Objects-Related Classes
Networking Functionality
Pathfinding-Related Classes
Physics-Related Classes
Plugins-Related Classes
IG Plugin
CIGIConnector Plugin
Rendering-Related Classes
VR-Related Classes
Работа с контентом
Оптимизация контента
Материалы
Визуальный редактор материалов
Material Nodes Library
Miscellaneous
Input
Math
Matrix
Textures
Art Samples
Учебные материалы

Ключевые слова и типы UUSL

This documentation article contains information about keywords, data types, pre-defined variables, constants and other features of the UUSL. This information can be used as the reference document for writing shaders. Эта статья документации содержит информацию о ключевых словах, типах данных, предварительно определенных переменных, константах и ​​других функциях UUSL. Эту информацию можно использовать в качестве справочного документа для написания шейдеров.

To start using UUSL, include the core/materials/shaders/render/common.h file. Чтобы начать использовать UUSL, включите файл core/materials/shaders/render/common.h.

UUSL
#include <core/materials/shaders/render/common.h>

This header file is also used for fragment shader functions and scalar and double types and functions.Этот заголовочный файл также используется для функций фрагментного шейдера и для скалярных и двойных типов и функций.

Data TypesТипы данных#

This articles contains different data types of UUSL. Эта статья содержит различные типы данных UUSL.

UUSL OpenGL Direct3D Описание
int2 ivec2 int2 A vector with two 32-bit signed integer components. Вектор с двумя 32-битными целочисленными компонентами со знаком.
int3 ivec3 int3 A vector with three 32-bit signed integer components. Вектор с тремя 32-битными целочисленными компонентами со знаком.
int4 ivec4 int4 A vector with four 32-bit signed integer components. Вектор с четырьмя 32-битными целочисленными компонентами со знаком.
uint2 uvec2 int2 A vector with two 32-bit unsigned integer components. Вектор с двумя 32-битными целочисленными компонентами без знака.
uint3 uvec3 uint3 A vector with three 32-bit unsigned integer components. Вектор с тремя 32-битными целочисленными компонентами без знака.
uint4 uvec4 uint4 A vector with four 32-bit unsigned integer components. Вектор с четырьмя 32-битными целочисленными компонентами без знака.
float float float float float float A 32-bit floating point value. 32-битное значение с плавающей запятой.
float2 vec2 float2 A vector with two 32-bit floating point value components. Вектор с двумя 32-битными компонентами значения с плавающей запятой.
float3 vec3 float3 A vector with three 32-bit floating point value components. Вектор с тремя 32-битными компонентами значений с плавающей запятой.
float4 vec4 float4 A vector with four 32-bit floating point value components. Вектор с четырьмя 32-битными компонентами значений с плавающей запятой.
float2x2 mat2 float2x2 A matrix with 2 rows, 2 columns of 32-bit floating point value components. Матрица с 2 строками, 2 столбцами 32-битных компонентов значений с плавающей запятой.
float3x3 mat3 float3x3 A matrix with 3 rows, 3 columns of 32-bit floating point value components. Матрица с 3 строками, 3 столбцами 32-битных компонентов значений с плавающей запятой.
float4x4 mat4 float4x4 A matrix with 4 rows, 4 columns of 32-bit floating point value components. Матрица с 4 строками, 4 столбцами 32-битных компонентов значений с плавающей запятой.
double2 dvec2 double2 A vector with two 64-bit double-precision floating point value components. Вектор с двумя 64-битными компонентами значений с плавающей запятой двойной точности.
double3 dvec3 double3 A vector with three 64-bit double-precision floating point value components. Вектор с тремя 64-битными компонентами значений с плавающей запятой двойной точности.
double4 dvec4 double4 A vector with four 64-bit double-precision floating point value components. Вектор с четырьмя 64-битными компонентами значений с плавающей запятой двойной точности.
double2x2 dmat2 double2x2 A matrix with 2 rows, 2 columns of 64-bit double-precision floating point value components. Матрица с 2 строками, 2 столбцами 64-битных компонентов значений с плавающей запятой двойной точности.
double3x3 dmat3 double3x3 A matrix with 3 rows, 3 columns of 64-bit double-precision floating point value components. Матрица с 3 строками, 3 столбцами 64-битных компонентов значений с плавающей запятой двойной точности.
double4x4 dmat4 double4x4 A matrix with 4 rows, 4 columns of 64-bit double-precision floating point value components. Матрица с 4 строками, 4 столбцами 64-битных компонентов значений с плавающей запятой двойной точности.
scalar float / double float / double A scalar value, which can be either float or double depending on precision (UNIGINE_DOUBLE flag). Скалярное значение, которое может быть либо float , либо double в зависимости от точности (флаг UNIGINE_DOUBLE).
scalar2 vec2 / dvec2 float2 / double2 A vector consisting of two scalar components, which can be either float or double depending on precision (UNIGINE_DOUBLE flag). Вектор, состоящий из двух скалярных компонентов, которые могут быть float или double в зависимости от точности (флаг UNIGINE_DOUBLE).
scalar3 vec3 / dvec3 float3 / double3 A vector consisting of three scalar components, which can be either float or double depending on precision (UNIGINE_DOUBLE flag). Вектор, состоящий из трех скалярных компонентов, которые могут быть float или double в зависимости от точности (флаг UNIGINE_DOUBLE).
scalar4 vec4 / dvec4 float4 / double4 A vector consisting of four scalar components, which can be either double or float depending on precision (UNIGINE_DOUBLE flag). Вектор, состоящий из четырех скалярных компонентов, которые могут быть либо double , либо float в зависимости от точности (флаг UNIGINE_DOUBLE).


Use these variable aliases when working with textures to make your shader's code readable:

Используйте эти псевдонимы переменных при работе с текстурами, чтобы код вашего шейдера был читабельным:

UUSL OpenGL Direct3D Описание
TYPE_R float float A 32-bit floating point value. 32-битное значение с плавающей запятой.
TYPE_RG float2 float2 A vector with two 32-bit floating point value components. Вектор с двумя 32-битными компонентами значения с плавающей запятой.
TYPE_RGB float3 float3 A vector with three 32-bit floating point value components. Вектор с тремя 32-битными компонентами значений с плавающей запятой.
TYPE_RGBA float4 float4 A vector with four 32-bit floating point value components. Вектор с четырьмя 32-битными компонентами значений с плавающей запятой.
TYPE_INT int int A 32-bit signed integer value. 32-битное целое число со знаком.
TYPE_UINT uint uint A 32-bit unsigned integer value. 32-битное целое число без знака.

Functions for type casting are the same for both DirectX and OpenGL: Функции приведения типов одинаковы как для DirectX, так и для OpenGL:

Функция Описание
int to_int(v) Create an integer from the value. Создает целое число из значения.
int2 to_int2(v) Create a two-component integer vector from the value. Создает двухкомпонентный целочисленный вектор из значения.
int3 to_int3(v) Create a three-component integer vector from the value. Создает трехкомпонентный целочисленный вектор из значения.
int4 to_int4(v) Create a four-component integer vector from the value. Создает четырехкомпонентный целочисленный вектор из значения.
uint to_uint(v) Create an unsigned integer from the value. Создать беззнаковое целое число из значения.
uint2 to_uint2(v) Create a two-component unsigned integer vector from the value. Создает двухкомпонентный целочисленный вектор без знака из значения.
uint3 to_uint3(v) Create a three-component unsigned integer vector from the value. Создает трехкомпонентный целочисленный вектор без знака из значения.
uint4 to_uint4(v) Create a four-component unsigned integer vector from the value. Создает четырехкомпонентный целочисленный вектор без знака из значения.
float to_float(v) Create a float from the value. Создает из значения число с плавающей запятой.
float2 to_float2(v) Create a two-component floating-point vector from the value. Создает двухкомпонентный вектор с плавающей запятой из значения.
float3 to_float3(v) Create a three-component floating-point vector from the value. Создает трехкомпонентный вектор с плавающей запятой из значения.
float4 to_float4(v) Create a four-component floating-point vector from the value. Создает четырехкомпонентный вектор с плавающей запятой из значения.
float4 to_gvec4(float v) Create a four-component floating-point vector from the value. Создает четырехкомпонентный вектор с плавающей запятой из значения.
float4 to_gvec4(float2 v) Create a four-component floating-point vector from the two-component floating-point vector. Создает четырехкомпонентный вектор с плавающей запятой из двухкомпонентного вектора с плавающей запятой.
float4 to_gvec4(float3 v) Create a four-component floating-point vector from the three-component floating-point vector. Создает четырехкомпонентный вектор с плавающей запятой из трехкомпонентного вектора с плавающей запятой.
float4 to_gvec4(float4 v) Create a four-component floating-point vector from the four-component floating-point vector. Создает четырехкомпонентный вектор с плавающей запятой из четырехкомпонентного вектора с плавающей запятой.
int4 to_gvec4(int v) Create a four-component integer vector from the integer value. Создает четырехкомпонентный целочисленный вектор из целочисленного значения.
int4 to_gvec4(int2 v) Create a four-component integer vector from the two-component integer vector. Создает четырехкомпонентный целочисленный вектор из двухкомпонентного целочисленного вектора.
int4 to_gvec4(int3 v) Create a four-component integer vector from the three-component integer vector. Создает четырехкомпонентный целочисленный вектор из трехкомпонентного целочисленного вектора.
int4 to_gvec4(int4 v) Create a four-component integer vector from the four-component integer vector. Создает четырехкомпонентный целочисленный вектор из четырехкомпонентного целочисленного вектора.
uint4 to_gvec4(uint v) Create a four-component unsigned integer vector from the unsigned integer value. Создает четырехкомпонентный вектор целого числа без знака из значения целого числа без знака.
uint4 to_gvec4(uint2 v) Create a four-component unsigned integer vector from the two-component unsigned integer vector. Создает четырехкомпонентный целочисленный вектор без знака из двухкомпонентного целочисленного вектора без знака.
uint4 to_gvec4(uint3 v) Create a four-component integer vector from the three-component unsigned integer vector. Создает четырехкомпонентный целочисленный вектор из трехкомпонентного целочисленного вектора без знака.
uint4 to_gvec4(uint4 v) Create a four-component unsigned integer vector from the four-component unsigned integer vector. Создает четырехкомпонентный целочисленный вектор без знака из четырехкомпонентного целочисленного вектора без знака.
double to_double(v) Create a double-precision value from the value. Создает значение двойной точности из значения.
double2 to_double2(v) Create a two-component double-precision vector from the value. Создает двухкомпонентный вектор двойной точности из значения.
double3 to_double3(v) Create a three-component double-precision vector from the value. Создает трехкомпонентный вектор двойной точности из значения.
double4 to_double4(v) Create a four-component double-precision vector from the value. Создает четырехкомпонентный вектор двойной точности из значения.
scalar to_scalar(v) Create a scalar value from the value. Создает скалярное значение из значения.
scalar2 to_scalar2(v) Create a two-component scalar value from the value. Создает двухкомпонентное скалярное значение из значения.
scalar3 to_scalar3(v) Create a three-component scalar value from the value. Создает трехкомпонентное скалярное значение из значения.
scalar4 to_scalar4(v) Create a four-component scalar value from the value. Создает четырехкомпонентное скалярное значение из значения.

Defined ValuesОпределенные значения#

UUSL Value
float_isrgb 2.233333f
float4_zero float4(0.0f,0.0f,0.0f,0.0f)
float4_one float4(1.0f,1.0f,1.0f,1.0f)
float4_half float4(0.5f,0.5f,0.5f,0.5f)
float4_neg_one float4(-1.0f,-1.0f,-1.0f,-1.0f)
float4_isrgb float4(float_isrgb,float_isrgb,float_isrgb,float_isrgb)
float3_zero float3(0.0f,0.0f,0.0f)
float3_one float3(1.0f,1.0f,1.0f)
float3_half float3(0.5f,0.5f,0.5f)
float3_neg_one float3(-1.0f,-1.0f,-1.0f)
float3_up float3(0.0f,0.0f,1.0f)
float3_isrgb float3(float_isrgb,float_isrgb,float_isrgb)
float3_epsilon float3(EPSILON,EPSILON,EPSILON)
float3_luma float3(0.299f,0.587f,0.114f)
float2_zero float2(0.0f,0.0f)
float2_one float2(1.0f,1.0f)
float2_half float2(0.5f,0.5f)
float2_neg_one float2(-1.0f,-1.0f)
float2_isrgb float2(float_isrgb,float_isrgb)
int4_zero int4(0,0,0,0)
int4_one int4(1,1,1,1)
int4_neg_one int4(-1,-1,-1,-1)
int3_zero int3(0,0,0)
int3_one int3(1,1,1)
int3_neg_one int3(-1,-1,-1)
int2_zero int2(0,0)
int2_one int2(1,1)
int2_neg_one int2(-1,-1)
double3_zero double3(DF(0.0),DF(0.0),DF(0.0))
double3_one double3(DF(1.0),DF(1.0),DF(1.0))
float4x4_identity float4x4(1.0f,0.0f,0.0f,0.0f,0.0f,1.0f,0.0f,0.0f,0.0f,0.0f,1.0f,0.0f,0.0f,0.0f,0.0f,1.0f)
PI 3.141592654f
PI2 6.283185308f
PI05 1.570796327f
LOG2 0.693147181f
LOG10 2.302585093f
SQRT2 1.414213562f
EPSILON 1e-6f
INT_MAX 4294967294
INFINITY 1e+9f
DEG2RAD PI / 180.0f
RAD2DEG 180.0f / PI
BYTE_UNORM_STEP 1.0f / 255.0f
WIREFRAME_DEPTH_BIAS -0.001f - if s_taa is 1.0f; otherwise, -0.0001f
STATICARRAY (float2,halton16,16) Array containing Halton sequence.
STATICARRAY (float2,halton8,8) Array containing Halton sequence.
STATICARRAY (uint,dither_pattern,16) Array containing disperced dither pattern.
STATICARRAY (float4,blue_noise_16x16,256) Array containing blue noise texture.

Use the following defined values in double-precision functions. Используйте следующие определенные значения в функциях двойной точности .

PI_D DF(3.14159265358979323846)
PI2_D DF(6.28318530717958647693)
IPI2_D DF(0.15915494309189533576)
PI05_D DF(1.57079632679489661923)
DEG2RAD_D DF(0.01745329251994329577)
RAD2DEG_D DF(57.29577951308232087685)
EPSILON_D 1e-7

Bit masking defined valuesОпределенные значения для битовых масок#

The following defined values are reserved bits of the Material mask. Следующие определенные значения являются зарезервированными битами маски Material .

SSAO_BIT 1<<31
SSR_BIT 1<<30
SSS_BIT 1<<29
DOF_BIT 1<<28
MOTION_BLUR_BIT 1<<27
SHADOW_SHAFTS_BIT 1<<26
LIGHTMAP_WITH_AMBIENT_BIT 1<<25
SHORELINE_WETNESS_BIT 1<<24
FREE_MATERIAL_MASK 1<<0x00FFFFFF
RESERVED_MATERIAL_MASK 1<<0xFF000000

Main FunctionФункция Main#

Void Main FunctionФункция Main Void#

To start and end the void Main function of the fragment shader (when you don't need to provide the output color value but depth), use the following instructions: Чтобы запустить и завершить функцию void Main фрагментного шейдера (когда вам не нужно указывать значение выходного цвета, а глубину), используйте следующие инструкции:

UUSL
STRUCT_FRAG_BEGIN
STRUCT_FRAG_END

MAIN_FRAG_BEGIN(FRAGMENT_IN)
	<your code here>
MAIN_FRAG_END

This code is equivalent to: Этот код эквивалентен:

OpenGL
void main() {
	<your code here>
}
Direct3D
void main(FRAGMENT_IN IN) {
	<your code here>
}

Main Function with Return ValueФункция Main с возвращаемым значением#

To start and end the Main function with return value, use the following instructions: Чтобы запустить и завершить функцию Main с возвращаемым значением, используйте следующие инструкции:

UUSL
STRUCT_FRAG_BEGIN
    INIT_COLOR(float4)
STRUCT_FRAG_END

MAIN_FRAG_BEGIN(FRAGMENT_IN)
	<your code here>
MAIN_FRAG_END

This code is equivalent to: Этот код эквивалентен:

OpenGL
void main() {
	<your code here>
}
Direct3D
FRAGMENT_OUT main(FRAGMENT_IN IN) { 
	FRAGMENT_OUT OUT;
	<your code here>
return OUT; }

Geometry Shader Main FunctionФункция Main геометрического шейдера#

To start and end the Main function of the geometry shader, use the following instructions: Чтобы запустить и завершить функцию Main геометрического шейдера, используйте следующие инструкции:

UUSL
STRUCT(GEOMETRY_IN)
	INIT_POSITION
	<input members>
END

STRUCT(GEOMETRY_OUT)
	INIT_POSITION
	<output members>
END

MAIN_GEOM_BEGIN(GEOMETRY_OUT, GEOMETRY_IN)
	<your code here>
MAIN_GEOM_END

This code is equivalent to: Этот код эквивалентен:

OpenGL
layout(TYPE_GEOM_IN) in;
layout(TYPE_GEOM_OUT,max_vertices = MAX_VERTICES_GEOM) out;
void main() {
	<your code here>
}
Direct3D
[maxvertexcount(MAX_VERTICES_GEOM)]
void main(TYPE_GEOM_IN GEOMETRY_IN IN[COUNT_GEOM_IN],inout TYPE_GEOM_OUT<GEOMETRY_OUT> stream) {
	GEOMETRY_OUT OUT;
	<your code here>
}

Global VariablesГлобальные переменные#

To define a global variable, use the following syntax: Чтобы определить глобальную переменную, используйте следующий синтаксис:

UUSL
GLOBAL <your var>

This is equal to the following GLSL and HLSL commands: Это эквивалентно следующим командам GLSL и HLSL:

OpenGL
uniform <your var>
Direct3D
uniform <your var>

Static Variables and ArraysСтатические переменные и массивы#

Static VariablesСтатические переменные#

To define a static variable, use the following syntax: Чтобы определить статическую переменную, используйте следующий синтаксис:

UUSL
STATICVAR <your var>

This is equal to the following GLSL and HLSL commands: Это эквивалентно следующим командам GLSL и HLSL:

OpenGL
const <your var>
Direct3D
static const <your var>

Static ArraysСтатические массивы#

To work with static arrays by using UUSL, use the following instructions: Для работы со статическими массивами с использованием UUSL используйте следующие инструкции:

UUSL
STATICARRAY(TYPE,NAME,SIZE)
	<your array members>
ENDARRAY
  • TYPE - the type of the array (float, etc.). TYPE - тип массива (float и т. д.).
  • NAME - the name of the array. NAME - имя массива.
  • SIZE - the size of the array. SIZE - размер массива.

This code block is equivalent to: Этот блок кода эквивалентен:

OpenGL
TYPE NAME [SIZE] = TYPE[](<your array members>);
Direct3D
static const TYPE NAME [SIZE] = {<your array members>};

Blending PresetsПредустановки смешивания#

UUSL contains blending presets. When you specify the type of blending in material, the USSL wrapper automatically defines a new definition, that you can use in your shader: UUSL содержит предустановки смешивания. Когда вы указываете тип смешивания в материале, оболочка USSL автоматически определяет новое определение, которое вы можете использовать в своем шейдере:

Blending type UUSL
BLEND_SRC_FUNC_SRC_ALPHA && BLEND_DEST_FUNC_ONE_MINUS_SRC_ALPHA BLEND_ALPHABLEND
BLEND_SRC_FUNC_ONE && BLEND_DEST_FUNC_ONE BLEND_ADDITIVE
BLEND_SRC_FUNC_DEST_COLOR && BLEND_DEST_FUNC_ZERO BLEND_MULTIPLICATIVE
BLEND_SRC_FUNC_NONE && BLEND_DEST_FUNC_NONE BLEND_NONE

HLSL featuresВозможности HLSL#

HLSL Flow Control AttributesАтрибуты управления потоком HLSL#

UUSL OpenGL Direct3D Описание
branch - [branch] Performs branching using control flow instructions. Выполняет ветвление с использованием инструкций потока управления.
call - [call] Prevents inlining of a function. Предотвращает встраивание функции.
flatten - [flatten] Performs branching using conditional move instructions. Выполняет ветвление с использованием инструкций условного перемещения.
ifAll - [ifAll] Executes the conditional part of an if statement when the condition is true for all threads on which the current shader is running. Выполняет условную часть оператора if , когда условие истинно для всех потоков, в которых работает текущий шейдер.
ifAny - [ifAny] Executes the conditional part of an if statement when the condition is true for any thread on which the current shader is running. Выполняет условную часть оператора if , когда условие истинно для любого потока, в котором выполняется текущий шейдер.
isolate - [isolate] Optimizes the specified HLSL code independently of the surrounding code. Оптимизирует указанный код HLSL независимо от окружающего кода.
loop - [loop] Gives preference to flow control constructs. Отдает предпочтение конструкциям управления потоком.
maxexports - [maxexports] Specifies the maximum number of export instructions that will execute along any path from the entry point to an exit. Задает максимальное количество инструкций экспорта, которые будут выполняться на любом пути от точки входа до точки выхода.
maxInstructionCount - [maxInstructionCount] Sets the maximum number of instructions available to a shader. Устанавливает максимальное количество инструкций, доступных шейдеру.
maxtempreg - [maxtempreg] Restricts temporary register usage to the number of registers specified. Generates a compiler error if unsuccessful. Ограничивает использование временных регистров указанным количеством регистров. В случае неудачи генерирует ошибку компилятора.
noExpressionOptimizations - [noExpressionOptimizations] Avoids optimization of expressions. Избегает оптимизации выражений.
predicate - [predicate] Performs branching by using predication. Выполняет ветвление с использованием предикации.
predicateBlock - [predicateBlock] Performs branching by using predicated exec blocks. Выполняет ветвление, используя предопределенные блоки exec .
reduceTempRegUsage - [reduceTempRegUsage] Restricts temporary register usage to the number of registers specified. Generates a compiler warning if unsuccessful. Ограничивает использование временных регистров указанным количеством регистров. В случае неудачи генерирует предупреждение компилятора.
removeUnusedInputs - [removeUnusedInputs] Removes unused interpolator inputs from pixel shaders. Удаляет неиспользуемые входные данные интерполятора из пиксельных шейдеров.
sampreg - [sampreg] Sets the ranges of pixel sampler and vertex sampler registers used by the compiler. Устанавливает диапазоны регистров сэмплера пикселей и вершинных сэмплеров, используемых компилятором.
unroll - [unroll] Avoids flow control constructs. Избегает конструкций управления потоком.
unused - [unused] Suppresses warnings about unused shader parameters. Подавляет предупреждения о неиспользуемых параметрах шейдера.
xps - [xps] Specifies that all vertex fetch operations are done after the last vfetch instruction. This instruction is used to reduce the latency back to the command processor to free the vertex buffer. Указывает, что все операции выборки вершин выполняются после последней инструкции vfetch. Эта инструкция используется для уменьшения задержки обратно в командный процессор, чтобы освободить буфер вершин.
earlydepthstencil - [earlydepthstencil] Forces depth-stencil testing before a shader executes. Doesn't work with custom depth. Принудительное тестирование трафарета глубины перед выполнением шейдера. Не работает с настраиваемой глубиной.

Interpolation ModifiersМодификаторы интерполяции#

UUSL OpenGL Direct3D Описание
MODIFER_LINEAR - linear Interpolate between shader inputs; linear is the default value if no interpolation modifier is specified. Интерполировать входные данные шейдера; linear - значение по умолчанию, если не указан модификатор интерполяции.
MODIFER_CENTROID - centroid Interpolate between samples that are somewhere within the covered area of the pixel (this may require extrapolating end points from a pixel center). Centroid sampling may improve antialiasing if a pixel is partially covered (even if the pixel center is not covered). The centroid modifier must be combined with either the linear or noperspective modifier. Интерполировать между выборками, которые находятся где-то в пределах покрываемой области пикселя (для этого может потребоваться экстраполяция конечных точек из центра пикселя). Выборка центроидов может улучшить сглаживание, если пиксель частично покрыт (даже если центр пикселя не покрыт). Модификатор центроида должен сочетаться с модификатором linear или noperspective.
MODIFER_NOINTERPOLATION - nointerpolation Do not interpolate. Не интерполировать.
MODIFER_NOPERSPECTIVE - noperspective Do not perform perspective-correction during interpolation. The noperspective modifier can be combined with the centroid modifier. Не выполнять коррекцию перспективы во время интерполяции. Модификатор noperspective можно комбинировать с модификатором центроида.
MODIFER_SAMPLE - sample Interpolate at sample location rather than at the pixel center. This causes the pixel shader to execute per-sample rather than per-pixel. Интерполировать в местоположении образца, а не в центре пикселя. Это заставляет пиксельный шейдер выполняться по выборке, а не по пикселям.

See AlsoСмотрите также#

See also the article on Interpolation Modifiers. См. также статью о модификаторах интерполяции.

Constants and StructsКонстанты и структуры#

StructsСтруктуры#

In USSL structs is the way to organize the bunch of input and output data. В структурах USSL - это способ организации связки входных и выходных данных.

To start using structs in your shader code, use the following instructions: Чтобы начать использовать структуры в коде шейдера, используйте следующие инструкции:

UUSL
STRUCT(NAME)
	<your data>
END
  • NAME - the name of the struct. NAME - имя структуры.

Here is an example of vertex shader input struct: Вот пример входной структуры вершинного шейдера:

UUSL
// Input vertex data
STRUCT(VERTEX_IN)
	INIT_ATTRIBUTE(float4,0,POSITION)	// Vertex position
	INIT_ATTRIBUTE(float4,1,TEXCOORD0)	// Vertex texcoord (uv)
	INIT_ATTRIBUTE(float4,2,TEXCOORD1)	// Vertex basis tangent
	INIT_ATTRIBUTE(float4,3,TEXCOORD2)	// Vertex color
END

After that, you should pass the VERTEX_IN struct to the main function of the vertex shader. После этого вы должны передать структуру VERTEX_IN в основную функцию вершинного шейдера.

ConstantsКонстанты#

For using constant buffer in your shader code, use the following instructions: Для использования буфера констант в коде шейдера используйте следующие инструкции:

UUSL
CBUFFER(NAME)
	<your data>
END
  • NAME - the name of the cbuffer. NAME - имя буфера.

Here is an example of using constant buffer: Вот пример использования постоянного буфера:

UUSL
CBUFFER(parameters)
	UNIFORM float grayscale_power;
END

If you defined this parameter in the material, you'll be able to specify this value. Если вы определили этот параметр в материале, вы сможете указать это значение.

See AlsoСмотрите также#

  • How to use the CBUFFER instruction in the tutorial on shaders for post-process pass. Как использовать инструкцию CBUFFER в учебнике по шейдерам для пост-обработки.

For LoopЦикл for#

There is a for loop implemented in UUSL: В UUSL реализован цикл for:

UUSL
forloop(NAME,BEGIN,END)
UUSL
for(int NAME = (BEGIN); NAME < (END); NAME++)

The keyword for is used to describe a loop that is controlled by a counter (NAME). The parentheses enclose three expressions that initialize, check and update the variable used as counter. The body defined by curly braces encloses the statements that are executed at each pass of the loop. Ключевое слово for используется для описания цикла, который контролируется счетчиком ( NAME ). В круглые скобки заключены три выражения, которые инициализируют, проверяют и обновляют переменную, используемую как счетчик. Тело, определенное фигурными скобками, включает в себя операторы, которые выполняются на каждом проходе цикла.

Here is an example of a for loop: Вот пример цикла for:

UUSL
forloop(i, 0, 99)
{
	aFunction();
}

Shader ExportЭкспорт шейдеров#

To export shader, use the following command: Чтобы экспортировать шейдер, используйте следующую команду:

UUSL
EXPORT_SHADER(FILE)
  • FILE - The name of the file. FILE - Имя файла.

This command exports the shader program into a file: for Direct3D the file will have an .hlsl extension, for OpenGL the file will have an .glsl extension. Эта команда экспортирует программу шейдера в файл: для Direct3D файл будет иметь расширение .hlsl, для OpenGL файл будет иметь расширение .glsl.

The command expands all of the predefined UUSL syntax and creates shader files in native languages for both graphic APIs. Команда расширяет весь предопределенный синтаксис UUSL и создает файлы шейдеров на собственных языках для обоих графических API.

Последнее обновление: 30.11.2023
Build: ()