Ru/Shader: Difference between revisions

From Valve Developer Community
< Ru
Jump to navigation Jump to search
(translation update)
(translation update)
Line 4: Line 4:
}}
}}


'''Шейдер''' это программа которая запускается на [https://ru.wikipedia.org/wiki/Графический_процессор графической процессоре] чтобы определить, как объект должен быть отрисован. Source uses shaders for everything in the 3D world.
'''Шейдер''' это программа которая запускается на [https://ru.wikipedia.org/wiki/Графический_процессор графической процессоре] чтобы определить, как объект должен быть отрисован. Source использует шейдеры для всего в 3D мире.


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.
Шейдеры манипулируют управляются параметрами, содержащимися в файлах [[Material:ru | Материалов]]. В то время как самые распространенные довольно просты, существуют очень сложные для обработки таких эффектов, как тени в реальном времени, освещение и преломление.


== Типы ==
== Типы ==


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 включает множество [[:Category:Shaders | существующих шейдеров ]].


== Шейдерные языки ==
== Шейдерные языки ==
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.
В настоящее время существует три основных языка шейдеров: [[HLSL|High Level Shader Language (HLSL)]], [[CG|C for Graphics (Cg)]] и [[Wikipedia:GLSL | OpenGL Shading Language (GLSL)]]. Source engine использует шейдеры на основе [[HLSL]]. Однако Cg очень схож с Cg шейдерами поэтому может быть быстро и просто портирован под HLSL.


== Шейдерные модели ==
== Шейдерные модели ==
Line 61: Line 61:
  }
  }


== Pixel shaders ==
== Пиксельные шейдеры ==
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.


Line 86: Line 86:


== Applications of shaders in Source ==
== 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.
Source Engine поставляет две отдельные формы шейдеров, Постпроцесс и Pre-Object, большинство эффектов и материалов используемых в Source Engine, в сильно зависят от компонентов пиксельного шейдера.


=== Postprocess ===
=== Постпроцесс ===
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.
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.



Revision as of 16:55, 12 March 2021

Template:Otherlang2

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

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

Типы

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

Шейдерные языки

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

Шейдерные модели

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.

Note.pngПримечание:Shaders written for SM3 may not work properly on Mac and Linux systems due to lack of support in Valve's runtime graphics wrapper, togl. You should plan to make a SM2.0b version of your shaders if you plan on supporting these systems.

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 article.

For information on authoring shaders for use in the Source engine, please see Shader Authoring.

Vertex шейдеры

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.

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

Примеры vertex шейдеров

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
#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.

// specify a texture sampler, the actual source of this is specified in a vmt
sampler2D Texture0 : register( s0 );
// 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 );
// 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);
// return the pixel colour in the form of a float4. return grey; }

Applications of shaders in Source

Source Engine поставляет две отдельные формы шейдеров, Постпроцесс и Pre-Object, большинство эффектов и материалов используемых в Source Engine, в сильно зависят от компонентов пиксельного шейдера.

Постпроцесс

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.pngПримечание: This information is out of date, and the files are no longer included in the SDK. sdk_bloom.cpp and sdk_bloom.ps20.fxc define one possible shader that could be used as an alternative example

The Source SDK provides an example of this form of shader in the postprocess files (sdk_postprocess.cpp, sdk_postprocess_vs20.fxc, and sdk_postprocess_ps20.fxc)

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

Per-object

A Per-Object shader in the Source engine is used on any object with the shader referenced in the relevant 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.

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)

External links