» Пиксельные шейдеры для новичков 02
This site relies heavily on Javascript. You should enable it if you want the full experience. Learn more.

Пиксельные шейдеры для новичков 02

English

02 "привет розовый мир"

Надеюсь, вы скачали архив .zip с файлами патчей и шейдеров для этого упражнения. Если нет, скачайте прямо сейчас

Распакуйте его и откройте файл "02_hello world in pink.v4p". Вы должны увидеть патч аналогичный нашему скриншоту.

Текстура "helo.png" рендерится два раза:
слева: оригинальная текстура, без каких-либо изменений.
справа: текстура обработанная шейдером.

02.1 Что делает шейдер с текстурой

Шейдер "проходится" по всем пикселям текстуры. Это означает, что шейдер применяет одинаковое правило к каждому пикселю текстуры.

Применяемое правило:

  • если пиксель белый, к нему применяется цвет из входного пина Color for Hello, установленный нодом  IOBox (Color).
  • если пиксель не белый, то ничего не происходит.

Будьте внимательны: в коде шейдера, значения для RGB устанавливаются от 0 до 1, а не от 0 до 255!

Вы видите, что вокруг букв пиксели не изменили свой цвет. Это происходит потому, что их цвет не совсем белый, скорее светло-серый... Чтобы избавиться от таких пикселей, мы должны определить порог чувствительности (threshold). На этом мы подробно остановимся в следующем упражнении chapter 3?.

02.2 Код

Теперь взглянем на код шейдера "02_hello world in pink.fx". Кликните правой кнопкой по ноду шейдера - в открывшемся окне вы видите код нашего шейдера.
Важные части кода отображаются контрастными цветами. Все остальное это комментарии, не существенные для поведения шейдера.

 // -------------------------
 // PARAMETERS:
 // -------------------------
 //transforms
 float4x4 tW: WORLD;        //the models world matrix 
 float4x4 tV: VIEW;         //view matrix as set via Renderer (DX9)
 float4x4 tP: PROJECTION;   //projection matrix as set via Renderer (DX9)
 float4x4 tWVP: WORLDVIEWPROJECTION;
 //texture
 texture Tex ~lt~string uiname="Texture";~gt~;
 sampler Samp = sampler_state   //sampler for doing the texture-lookup
 {
    Texture   = (Tex);          //apply a texture to the sampler
    MipFilter = LINEAR;         //sampler states
    MinFilter = LINEAR;
    MagFilter = LINEAR;
 };
 //texture transformation marked with semantic TEXTUREMATRIX to achieve symmetric transformations
 float4x4 tTex: TEXTUREMATRIX ~lt~string uiname="Texture Transform";~gt~;
 //creates a color pin with the default value black with alphachanel set to 1 and with pinname "Color for Hello"
 float4 HelloColor : COLOR ~lt~string uiname="Color for Hello";~gt~  = {  0.0,    0.0,    0.0,    1.00000  };
 //the data structure: "vertexshader to pixelshader" is used as output data with the VS function and as input data with the PS function
 struct vs2ps
 {
    float4 Pos : POSITION;
    float4 TexCd : TEXCOORD0;
 };
 //  -------------------------
 // VERTEXSHADERS
 // -------------------------
 vs2ps VS(
    float4 Pos : POSITION,
    float4 TexCd : TEXCOORD0)
 {
    //inititalize all fields of output struct with 0
    vs2ps Out = (vs2ps)0;
    //transform position
    Out.Pos = mul(Pos, tWVP);
    //transform texturecoordinates
    Out.TexCd = mul(TexCd, tTex);
    return Out;

}

 // -------------------------
 // PIXELSHADERS:
 // -------------------------
 float4 hello_01(vs2ps In): COLOR
 {
    //texture lookup to access the pixels of the texture
    float4 col = tex2D(Samp, In.TexCd);
    //if the pixels are white then overwrite them with HelloColor (above input color)
    //or do nothing
    //then return col
    if (col.r == 1 && col.g ==1 && col.b == 1)
    {
    col = HelloColor;
    }
    return col;
 }
 // -------------------------
 // TECHNIQUES:
 // -------------------------
 technique HelloInPink //name for the technique pin
 {
    pass P0
    {
        VertexShader = compile vs_1_1 VS();
        PixelShader  = compile ps_2_0 hello_01();
    }
 }

назад к списку уроков

anonymous user login

Shoutbox

~15d ago

~18d ago

joreg: The Winter Season of vvvv workshops is now over but all recordings are still available for purchase: https://thenodeinstitute.org/ws23-vvvv-intermediates/

~24d ago

schlonzo: Love the new drag and drop functionality for links in latest previews!

~1mth ago

joreg: Workshop on 29 02: Create Sequencers and Precise Clock Based Tools. Signup here: https://thenodeinstitute.org/courses/ws23-vvvv-08-create-sequencers-and-precise-clock-based-tools-in-vvvv-gamma/

~1mth ago

joreg: Workshop on 22 02: Unlocking Shader Artistry: A Journey through ‘The Book of Shaders’ with FUSE. Signup here: https://thenodeinstitute.org/courses/ws23-vvvv-12-book-of-shaders/

~2mth ago

joreg: Talk and Workshop on February 15 & 16 in Frankfurt: https://visualprogramming.net/blog/vvvv-at-node-code-frankfurt/

~2mth ago

woei: @Joanie_AntiVJ: think so, looks doable