GLSL 筆記


OpenGL 3.2 以後的 pipeline

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →


OpenGL GLSL info
2.0 1.10 110
2.1 1.20 120
3.0 1.30 130
3.1 1.40 140
3.2 1.50 150
3.3 3.30 330
4.0 之後以此類推 4.00 400
OpenGL ES GLSL ES WebGL info
2.0 1.00 (GLSL 1.20) 1.0 100
3.0 3.00 (GLSL 3.30) 2.0 300 es
//use openGL 3.0 #version 130
//use openGL ES 3.0 #version 300 es

GLSLangSpec

keyword
GL_ES openGL ES
uniform
gl_position
gl_FragColor ES 3.0 已移除
conditional compilation
#ifdef KEYWORD
#endif
is defined
#ifndef KEYWORD
#endif
not defined
precision range performance quality
highp high precision 16-bit
floating point range: -2^62 to 2^62
integer range: -2^16 to 2^16
low high
mediump medium precision 10 bit
floating point range: -2^14 to 2^14
integer range: -2^10 to 2^10
medium medium
lowp low precision 8 bit
floating point range: -2 to 2
integer range: -2^8 to 2^8
high low

使用中等精度的浮點數

#ifdef GL_ES
precision mediump float
#endif
qualifier
in function arg read-only
out function arg write-only
inout function arg read/write

uniform 變數由外部指定, 內部 read-only


glsl canvas 簡易測試

uniform 需要對應 glslcanvas.js 定義的名稱

<script type="text/javascript" src="https://unpkg.com/glsl-canvas-js/dist/umd/glsl-canvas.min.js"></script> <canvas class="glsl-canvas" data-fragment-url="target.frag" width="500" height="500"></canvas>
<canvas class="glsl-canvas" data-fragment-url="target.frag" data-textures="file.png" width="200" height="200"></canvas>

native function

  • step()

    ​​​​//edge > x return 0.0
    ​​​​//edge <= x return 1.0
    ​​​​float result = step(edge, x);
    
  • fract()

    ​​​​//return x - math.floor(x)
    ​​​​float result = fract(x);
    
  • atan()
    GLSL 沒有 atan2()


varying variable

A varying variable must be written on a vertex shader

In the fragment shader the variable, whose value results from an interpolation of the vertex values computed previously, can only be read.

shader access
vertex write/read
fragment read-only

ES 2.0 to 3.0

ES 2.0

//vertex shader
attribute vec2 texcoord;
varying vec2 texUV;
//fragment shader
varying vec2 texUV;
uniform sampler2D tex;

void main(){
    gl_FragColor = texture2D(tex, texUV);
}

ES 3.0 以後

//vertex shader
in vec2 texcoord;
out vec2 texUV;
//fragment shader
in vec2 texUV;
uniform sampler2D tex;

out vec4 fragColor;

void main(){
    fragColor = texture(tex, texUV);
}

輔助工具


tags: GLSL