GLSL學習筆記 – 6.3 Fragment Shader

來源:互聯網
上載者:User
程式判斷片斷是處於磚塊位置還是水泥位置,然後分別進行著色。

程式流程

使用內建函數說明:
  vec2 floor (vec2 x):               Returns a value equal to the nearest integer that
                                     is less than or equal to x.

  vec2 fract (vec2 x):               Returns x – floor (x).

  vec2 step (vec2 edge, vec2 x):     Returns 0 if x <= edge; otherwise, it returns 1.0.

  vec3 mix (vec3 x, vec3 y, vec3 a): Returns x * (1.0 – a) + y * a, i.e., the linear
                                     blend of x and y using the floating-point value a.
                                     The value for a is not restricted to the range [0,1].

得到當前片斷在整個磚塊圖案中的位置。(單位長度1 = 一個磚塊的尺寸)
position = MCposition / BrickSize;

每隔一行,位移半個磚塊寬度。產生交錯感。
if (fract(position.y * 0.5) > 0.5)
    position.x += 0.5;

得到當前片斷在磚塊圖的一個圖元中的相對位置。
position = fract(position);

判斷當前片斷處於磚塊位置還是灰泥位置,處於磚塊位置時為1,處於灰泥位置時為0。
useBrick = step(position, BrickPct);

根據當前片斷的位置,得到當前片斷的顏色值。
color  = mix(MortarColor, BrickColor, useBrick.x * useBrick.y);

在顏色中加入光照效果。
color *= LightIntensity;

將計算好的顏色賦給當前片斷。
gl_FragColor = vec4 (color, 1.0);


程式清單

uniform vec3  BrickColor, MortarColor;
uniform vec2  BrickSize;
uniform vec2  BrickPct;

varying vec2  MCposition;
varying float LightIntensity;

void main(void){
    vec3  color;
    vec2  position, useBrick;
    
    position = MCposition / BrickSize;

    if (fract(position.y * 0.5) > 0.5)
        position.x += 0.5;
    position = fract(position);

    useBrick = step(position, BrickPct);

    color  = mix(MortarColor, BrickColor, useBrick.x * useBrick.y);
    color *= LightIntensity;
    
    gl_FragColor = vec4 (color, 1.0);
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.