Ru/Shader: Difference between revisions

From Valve Developer Community
< Ru
Jump to navigation Jump to search
(Created page with "{{otherlang2 | title = Шейдер | en = Shader }} A '''shader''' is software which runs on a graphics card to determine how an obj...")
 
m (obsolete language category)
 
(24 intermediate revisions by 7 users not shown)
Line 1: Line 1:
{{otherlang2
{{LanguageBar|title = Оттенение}}
| title = Шейдер
{{see also|[[:Category:Shaders]]}}
| en = Shader
}}


A '''shader''' is software which runs on a [[Wikipedia:Graphics processing unit|graphics card]] to  determine how an object should be drawn. Source uses shaders for everything in the 3D world.


Shaders are manipulated with parameters stored in [[material]] files. While the most common are quite simple, very complex ones exist to handle effects like real-time shadowing, lighting and refraction.
'''Оттенение (Shader)''' - это набор команд, исполняемый на [https://ru.wikipedia.org/wiki/Графический_процессор графическом процессоре], чтобы определить, как объект должен быть отображён. Source использует оттенения для всего в 3D мире.


==Types==
Оттенением можно управлять посредством параметров, содержащихся в файлах {{L|Material|материалов}}. В то время как самые распространенные довольно просты, существуют очень сложные для обработки таких эффектов, как тени в реальном времени, освещение и преломление.


There are two variations of shaders, Pixel shaders and Vertex shaders, each of which performs a different task in the rendering pipeline. Shaders form a replacement for the fixed function pipeline and allow developers greater control over rendering output by providing the ability to modify pixels and vertices dynamically. The SDK includes many [[:Category:Shaders|existing shaders]].
== Типы ==
Существует две разновидности оттенений, Точечное оттенение и Вершинное оттенение, каждое из них выполняет разные задачи в конвейере данных рендера. Оттенения заменяют собой конвейер фиксированных функций и позволяет разработчикам лучшн управлять выводом отображения, предоставляя возможность динамического изменения пикселей и вершин*. SDK включает множество {{LCategory|Shaders|существующих оттенений}}.


== Shader languages ==
== Языки программирования ==
There are currently three main shader languages: [[HLSL|High Level Shader Language (HLSL)]], [[CG|C for Graphics (Cg)]] and [[Wikipedia:GLSL | OpenGL Shading Language (GLSL)]]. The Source engine uses [[HLSL]] based shaders. However Cg is so similar that most Cg shaders can be quickly and easily ported to HLSL.
В настоящее время существует три основных языка для программирования оттенений: {{L|HLSL|High Level Shader Language (HLSL)}}, {{L|CG|C for Graphics (Cg)}} и [[Wikipedia:GLSL | OpenGL Shading Language (GLSL)]]. Source engine использует оттенения на основе {{L|HLSL}}. Однако Cg очень схож с Cg шейдерами поэтому может быть быстро и просто портирован под HLSL.


== Shader models ==
== Спецификация оттенений ==
A shader model defines how ''advanced'' shading techniques are allowed to get on a graphics card. This prevents older graphics cards from being physically able to recognize newer shading techniques.
Используемая версия спецификации оттенения определяет насколько современные методы оттенения поддерживаются графической картой. Это не позволяет старым графическим картам физически распознавать новые методы оттенения.


Modern versions of [[Source]] support Shader Model 2.0 (including Pixel Shader 2.0b) and Shader Model 3.0.  
Современные версии {{Source|2}} поддерживают Shader Model 2.0 (включая Pixel Shader 2.0b) и Shader Model 3.0.  
{{Note|Shaders written for SM3 may not work properly on Mac and Linux systems due to lack of support in Valve's runtime graphics wrapper, <code>togl</code>. You should plan to make a SM2.0b version of your shaders if you plan on supporting these systems.}}
{{Note|Оттенения написанные под SM3 могут не работать должным образом на системах Mac и Linux из-за отсутствия поддержки Valve's runtime graphics wrapper, <code>togl</code>. Вы должны планировать сделать SM2.0b версию вашего оттенения, если Вы планируете поддерживать эти OC.}}


When creating shaders for newer graphics cards, it's important to remember to support those with older cards, or you will quickly limit the specs of your game to only a select few. Older cards can require so called "shader fallbacks" to be specified, where a backup shader (using an older shader model) will be used if the newer shader fails.
При создании оттенения под новые видеокарты важно не забывать поддерживать тех, у кого есть старые видеокарты иначе Вы сильно ограничите возможность использования вашей игры. Старые графические карты могут потребовать указания так называемых "резервных оттенений", когда резервное оттенение (с использованием более старой спецификации) будет использоваться в случае сбоя современного оттенения.


If you want to learn more about the detailed specs of different Shader Models, read the [[Wikipedia:High Level Shader Language|Wikipedia article]].
Если Вы хотите узнать подробнее о различный спецификациях оттенений, смотрите [[Wikipedia:High Level Shader Language|Статью в википедии]].


For information on authoring shaders for use in the Source engine, please see [[Shader Authoring]].
Дополнительные сведения о создании оттенений для использования на платформе Source см. в разделе {{L|Shader Authoring|Создание шейдеров}}.


== Vertex shaders ==
== Вершинное оттенение ==
Vertex shaders are applied for each vertex run on a programmable pipeline. Its most basic goal is to transform geometry into screenspace coordinates so that the Pixel shader can rasterize an image. Vertex shaders can modify these position coordinates to perform mesh deformation. They can also receive additional information from the mesh, including normals, tangents, and texture coordinates. The vertex shader then writes to output registers; the written values are then interpolated across the vertices in the pixel shaders. Vertex shaders cannot create vertices.
Вершинное оттенение применяются для каждой вершины, запущенной в программируемом конвейере. Its most basic goal is to transform geometry into screenspace coordinates so that the Pixel shader can rasterize an image. Vertex shaders can modify these position coordinates to perform mesh deformation. They can also receive additional information from the mesh, including normals, tangents, and texture coordinates. The vertex shader then writes to output registers; the written values are then interpolated across the vertices in the pixel shaders. Вершинное оттенение не создаёт реальные вершины.


A heavily commented example vertex shader, ready for use in Source is provided below.
Ниже приведен подробно прокомментированный пример вершинного оттенения, готовый к использованию в Source.


=== Example vertex shader ===
=== Пример Вершинного оттенения ===
This is a pass through shader - in so far as it makes no major modification to the vertex data, instead just passing the data through to the pixel shader stage.
This is a pass through shader - in so far as it makes no major modification to the vertex data, instead just passing the data through to the pixel shader stage.


// common vertex shader defines provided with this header
{{CodeBlock|lines=31|<nowiki>// common vertex shader defines provided with this header
#include "common_vs_fxc.h"<br>
#include "common_vs_fxc.h"
// define an output structure
struct VS_OUTPUT
{
  // position vector (float4)
  float4 pos      : POSITION0;
  // texture coordinates (uv - float2)
  float2 texCoord  : TEXCOORD0;
};<br>
// main function - note C style definition
// takes a position vector (float4)
// returns a VS_OUTPUT struct
VS_OUTPUT main( float4 inPos: POSITION )
{
  // declare an empty VS_OUTPUT to fill
  VS_OUTPUT o = (VS_OUTPUT) 0;<br>
  // compute the sign of the input position
  inPos.xy = sign( inPos.xy);
  // set the output position using the xy of the input
  o.pos = float4( inPos.xy, 0.0f, 1.0f);<br>
  // get into range [0,1]
  o.texCoord = (float2(o.pos.x, -o.pos.y) + 1.0f)/2.0f;
  return o;
}


== Pixel shaders ==
// define an output structure
struct VS_OUTPUT
{
// position vector (float4)
float4 pos      : POSITION0;
 
// texture coordinates (uv - float2)
float2 texCoord  : TEXCOORD0;
};
 
// main function - note C style definition
// takes a position vector (float4)
// returns a VS_OUTPUT struct
VS_OUTPUT main( float4 inPos: POSITION )
{
// declare an empty VS_OUTPUT to fill
VS_OUTPUT o = (VS_OUTPUT) 0;
 
// compute the sign of the input position
inPos.xy = sign( inPos.xy);
 
// set the output position using the xy of the input
o.pos = float4( inPos.xy, 0.0f, 1.0f);
 
// get into range [0,1]
o.texCoord = (float2(o.pos.x, -o.pos.y) + 1.0f)/2.0f;
return o;
}</nowiki>}}
 
== Точечное оттенение ==
Pixel shaders are applied for each pixel rendered to the screen. A pixel shader expects input from interpolated vertex values, which it then uses to rasterize the image. Pixel shaders can produce a huge range of effects involving the color of individual pixels such as refraction, per-pixel lighting or reflection.
Pixel shaders are applied for each pixel rendered to the screen. A pixel shader expects input from interpolated vertex values, which it then uses to rasterize the image. Pixel shaders can produce a huge range of effects involving the color of individual pixels such as refraction, per-pixel lighting or reflection.


A heavily commented example pixel shader, ready for use in Source is provided below.
A heavily commented example pixel shader, ready for use in Source is provided below.


=== Example pixel shader ===
=== Пример точечного оттенения ===
The pixel shader below is intended for use as a post-process shader and creates a grayscale effect.
The pixel shader below is intended for use as a post-process shader and creates a grayscale effect.


// specify a texture sampler, the actual source of this is specified in a vmt
{{CodeBlock|lines=15|<nowiki>// specify a texture sampler, the actual source of this is specified in a vmt
sampler2D Texture0 : register( s0 );<br>
sampler2D Texture0 : register( s0 );<br>
// same function declaration style as vertex shaders
// same function declaration style as vertex shaders
// pixel shaders return the colour value of the pixel (hence the float4)
// pixel shaders return the colour value of the pixel (hence the float4)
float4 main( float2 texCoord  : TEXCOORD0 ) : COLOR
float4 main( float2 texCoord  : TEXCOORD0 ) : COLOR
{
{
  // sample the texture at the specified texture coordinates
// sample the texture at the specified texture coordinates
  float4 tex = tex2D( Texture0, texCoord );<br>     
float4 tex = tex2D( Texture0, texCoord );<br>     
  // greyscale the pixel colour values
// greyscale the pixel colour values
  // - perform a dot product between the pixel colour and the specified vector
// - perform a dot product between the pixel colour and the specified vector
  // - 0.222, 0.707, 0.071 is found throughout image processing for gray scale effects.
// - 0.222, 0.707, 0.071 is found throughout image processing for gray scale effects.
  float4 grey = dot(float3(0.222, 0.707, 0.071), tex);<br>   
float4 grey = dot(float3(0.222, 0.707, 0.071), tex);<br>   
  // return the pixel colour in the form of a float4.           
// return the pixel colour in the form of a float4.           
  return grey;
return grey;
}
}</nowiki>}}
 
==Наложение оттенений в Source==
Платформа {{Source|2}} позволяет использовать два отличающихся вида оттенения, Постобработка и Объектное, большинство эффектов и материалов используемых на платформе {{Source|2}} в значительной степени определяются компонентами точечного оттенения.


== Applications of shaders in Source ==
===Постобработка===
The Source engine provides for two separate forms of shaders, Postprocess and Per-Object, the majority of the effects and materials used within the Source engine rely heavily on their Pixel shader components.
Постобработка, это обычное Пиксельное оттенение применённое к прямоугольной области изображения, отображаемым по всему экрану. Прямоугольная область содержит копию из кадрового-буфера, Пиксельный оттенение может заменить и модифицировать выходное отображение, чтобы создать разнообразные эффекты, например, базовая модификация цвета для более продвинутых процессов, таких как размытие движения и свечение.


=== Postprocess ===
{{Note | Эта информация не актуальна и файлы более не включены в SDK. {{file|sdk_bloom|cpp}} и {{file|sdk_bloom.ps20|fxc}} определяют одно возможное оттенение, которое может быть использовано, как альтернативный пример.}}
A Postprocess shader is typically a Pixel shader that works on a quad rendered across the entire screen. The quad is textured with a copy of the frame buffer, the Pixel shader can then alter and modify the rendered output to create a variety of effects, such as basic color modification to more advanced processes such as motion blur and bloom.


{{Note| This information is out of date, and the files are no longer included in the SDK.  <code>sdk_bloom.cpp</code> and <code>sdk_bloom.ps20.fxc</code> define one possible shader that could be used as an alternative example}}
Source SDK предоставляет пример этого вида оттенения в файлах постобработки ({{file|sdk_postprocess.cpp|cpp}}, {{file|sdk_postprocess_vs20|fxc}}, и {{file|sdk_postprocess_ps20|fxc}})
The Source SDK provides an example of this form of shader in the postprocess files (<code>sdk_postprocess.cpp</code>, <code>sdk_postprocess_vs20.fxc</code>, and <code>sdk_postprocess_ps20.fxc</code>)


Advanced Postprocess shaders, such as the bloom and motion blur shaders included with source, may also need to use custom [[Render Targets]].  For more information on integrating a Postprocess shader with a mod, see [[Custom_Postprocessing_Effects]]
Продвинутая постобработка, такая как свечение и размытие движения, интегрированны на платформе {{Source|2}}, могут пригодиться для создании пользовательских {{L|Render_target|Целей Рендеринга}}


=== Per-object ===
===Объектное===
A Per-Object shader in the Source engine is used on any object with the shader referenced in the relevant [[VMT|Valve Material (.vmt)]] file, such as a model or piece of brushwork. A Per-Object shader could be used to create a refractive material, modify a models vertices dynamically or other advanced rendering effects.
Объектное оттенение на платформе {{Source|2}} используется на любом объекте, если ссылка на оттенение указана в применяемом файле {{L|VMT|материала (.vmt)}} , например модели или элементы карты. Объектное оттенение можно использовать для создания преломляющего материала, динамического изменения вершин модели или других расширенных эффектов отображения.


The Source SDK provides an example of a Per-Object shader in the lightmap files ( <code>sdk_lightmap.cpp</code>, <code>sdk_lightmap_vs20.fxc</code>, and <code>sdk_lightmap_ps20.fxc</code>)
The Source SDK provides an example of a Per-Object shader in the lightmap files ({{file|sdk_lightmap|cpp}}, {{file|sdk_lightmap_vs20|fxc}}, and {{file|sdk_lightmap_ps20|fxc}})


== External links ==
==Внешние ссылки==
* [http://www.bit-tech.net/hardware/2005/07/25/guide_to_shaders/1 A bluffer's guide to Shader Models]
* [https://www.bit-tech.net/hardware/2005/07/25/guide_to_shaders/1 A bluffer's guide to Shader Models]
* [http://http.developer.nvidia.com/CgTutorial/cg_tutorial_chapter01.html NVIDIA - The Cg tutorial]
* [https://http.developer.nvidia.com/CgTutorial/cg_tutorial_chapter01.html NVIDIA - The Cg tutorial]
* [https://developer.nvidia.com/gpugems/GPUGems/gpugems_part01.html NVIDIA - GPU Gems]
* [https://developer.nvidia.com/gpugems/GPUGems/gpugems_part01.html NVIDIA - GPU Gems]
* [https://developer.nvidia.com/gpugems/GPUGems2/gpugems2_part01.html NVIDIA - GPU Gems 2]
* [https://developer.nvidia.com/gpugems/GPUGems2/gpugems2_part01.html NVIDIA - GPU Gems 2]
* [https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_part01.html NVIDIA - GPU Gems 3]
* [https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_part01.html NVIDIA - GPU Gems 3]
* {{wiki|Shader}} - a Wikipedia article on the subject.
* {{wiki|Shader}} - a Wikipedia article on the subject.
* [http://www.moddb.com/games/half-life-2/tutorials/introduction-to-shaders Introduction to Shaders Tutorial from Wraiyth]
* [https://www.moddb.com/games/half-life-2/tutorials/introduction-to-shaders Introduction to Shaders Tutorial from Wraiyth]
* [http://www.moddb.com/games/half-life-2/tutorials/post-process-shader Post-Process Shader Tutorial from Wraiyth]
* [https://www.moddb.com/games/half-life-2/tutorials/post-process-shader Post-Process Shader Tutorial from Wraiyth]
 


{{ACategory|Glossary}}
{{ACategory|Programming}}
[[Category:Shaders:ru|*]]
{{ACategory|Technical}}


[[Category: Glossary]]
{{ACategory|Material_System}}
[[Category: Programming]]
[[Category: Shaders|*]]
[[Category: Technical]]

Latest revision as of 04:05, 22 August 2024

English (en)Español (es)Русский (ru)Українська (uk)中文 (zh)Translate (Translate)
См. также:  Category:Shaders


Оттенение (Shader) - это набор команд, исполняемый на графическом процессоре, чтобы определить, как объект должен быть отображён. Source использует оттенения для всего в 3D мире.

Оттенением можно управлять посредством параметров, содержащихся в файлах материалов(en). В то время как самые распространенные довольно просты, существуют очень сложные для обработки таких эффектов, как тени в реальном времени, освещение и преломление.

Типы

Существует две разновидности оттенений, Точечное оттенение и Вершинное оттенение, каждое из них выполняет разные задачи в конвейере данных рендера. Оттенения заменяют собой конвейер фиксированных функций и позволяет разработчикам лучшн управлять выводом отображения, предоставляя возможность динамического изменения пикселей и вершин*. SDK включает множество существующих оттенений(en).

Языки программирования

В настоящее время существует три основных языка для программирования оттенений: High Level Shader Language (HLSL)(en), C for Graphics (Cg)(en) и OpenGL Shading Language (GLSL). Source engine использует оттенения на основе HLSL(en). Однако Cg очень схож с Cg шейдерами поэтому может быть быстро и просто портирован под HLSL.

Спецификация оттенений

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

Современные версии Source Source поддерживают Shader Model 2.0 (включая Pixel Shader 2.0b) и Shader Model 3.0.

Note.pngПримечание:Оттенения написанные под SM3 могут не работать должным образом на системах Mac и Linux из-за отсутствия поддержки Valve's runtime graphics wrapper, togl. Вы должны планировать сделать SM2.0b версию вашего оттенения, если Вы планируете поддерживать эти OC.

При создании оттенения под новые видеокарты важно не забывать поддерживать тех, у кого есть старые видеокарты иначе Вы сильно ограничите возможность использования вашей игры. Старые графические карты могут потребовать указания так называемых "резервных оттенений", когда резервное оттенение (с использованием более старой спецификации) будет использоваться в случае сбоя современного оттенения.

Если Вы хотите узнать подробнее о различный спецификациях оттенений, смотрите Статью в википедии.

Дополнительные сведения о создании оттенений для использования на платформе Source см. в разделе Создание шейдеров(en).

Вершинное оттенение

Вершинное оттенение применяются для каждой вершины, запущенной в программируемом конвейере. Its most basic goal is to transform geometry into screenspace coordinates so that the Pixel shader can rasterize an image. Vertex shaders can modify these position coordinates to perform mesh deformation. They can also receive additional information from the mesh, including normals, tangents, and texture coordinates. The vertex shader then writes to output registers; the written values are then interpolated across the vertices in the pixel shaders. Вершинное оттенение не создаёт реальные вершины.

Ниже приведен подробно прокомментированный пример вершинного оттенения, готовый к использованию в Source.

Пример Вершинного оттенения

This is a pass through shader - in so far as it makes no major modification to the vertex data, instead just passing the data through to the pixel shader stage.

  1.  
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10.  
  11.  
  12.  
  13.  
  14.  
  15.  
  16.  
  17.  
  18.  
  19.  
  20.  
  21.  
  22.  
  23.  
  24.  
  25.  
  26.  
  27.  
  28.  
  29.  
  30.  
  31.  
// common vertex shader defines provided with this header #include "common_vs_fxc.h" // define an output structure struct VS_OUTPUT { // position vector (float4) float4 pos  : POSITION0; // texture coordinates (uv - float2) float2 texCoord  : TEXCOORD0; }; // main function - note C style definition // takes a position vector (float4) // returns a VS_OUTPUT struct VS_OUTPUT main( float4 inPos: POSITION ) { // declare an empty VS_OUTPUT to fill VS_OUTPUT o = (VS_OUTPUT) 0; // compute the sign of the input position inPos.xy = sign( inPos.xy); // set the output position using the xy of the input o.pos = float4( inPos.xy, 0.0f, 1.0f); // get into range [0,1] o.texCoord = (float2(o.pos.x, -o.pos.y) + 1.0f)/2.0f; return o; }

Точечное оттенение

Pixel shaders are applied for each pixel rendered to the screen. A pixel shader expects input from interpolated vertex values, which it then uses to rasterize the image. Pixel shaders can produce a huge range of effects involving the color of individual pixels such as refraction, per-pixel lighting or reflection.

A heavily commented example pixel shader, ready for use in Source is provided below.

Пример точечного оттенения

The pixel shader below is intended for use as a post-process shader and creates a grayscale effect.

  1.  
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10.  
  11.  
  12.  
  13.  
  14.  
  15.  
// specify a texture sampler, the actual source of this is specified in a vmt sampler2D Texture0 : register( s0 );<br> // same function declaration style as vertex shaders // pixel shaders return the colour value of the pixel (hence the float4) float4 main( float2 texCoord  : TEXCOORD0 ) : COLOR { // sample the texture at the specified texture coordinates float4 tex = tex2D( Texture0, texCoord );<br> // greyscale the pixel colour values // - perform a dot product between the pixel colour and the specified vector // - 0.222, 0.707, 0.071 is found throughout image processing for gray scale effects. float4 grey = dot(float3(0.222, 0.707, 0.071), tex);<br> // return the pixel colour in the form of a float4. return grey; }

Наложение оттенений в Source

Платформа Source Source позволяет использовать два отличающихся вида оттенения, Постобработка и Объектное, большинство эффектов и материалов используемых на платформе Source Source в значительной степени определяются компонентами точечного оттенения.

Постобработка

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

Note.pngПримечание: Эта информация не актуальна и файлы более не включены в SDK. 🖿sdk_bloom.cpp и 🖿sdk_bloom.ps20.fxc определяют одно возможное оттенение, которое может быть использовано, как альтернативный пример.

Source SDK предоставляет пример этого вида оттенения в файлах постобработки (🖿sdk_postprocess.cpp.cpp, 🖿sdk_postprocess_vs20.fxc, и 🖿sdk_postprocess_ps20.fxc)

Продвинутая постобработка, такая как свечение и размытие движения, интегрированны на платформе Source Source, могут пригодиться для создании пользовательских Целей Рендеринга(en)

Объектное

Объектное оттенение на платформе Source Source используется на любом объекте, если ссылка на оттенение указана в применяемом файле материала (.vmt)(en) , например модели или элементы карты. Объектное оттенение можно использовать для создания преломляющего материала, динамического изменения вершин модели или других расширенных эффектов отображения.

The Source SDK provides an example of a Per-Object shader in the lightmap files (🖿sdk_lightmap.cpp, 🖿sdk_lightmap_vs20.fxc, and 🖿sdk_lightmap_ps20.fxc)

Внешние ссылки