GLSL is OpenGL Shader programming language, in order to better video editing and special effects development, take time to learn its syntax and characteristics, and make this record, keep as a memo query.
type
Summary of the type
Variable categories | Variable types | note |
---|---|---|
empty | void | Void main(void); void main(void); |
scalar | bool/int/float | Boolean, integer, floating point |
Boolean vector | bvec2/bvec3/bvec4 | Among themb Represents the vector type, and the number represents the number of components of the vector |
The integer vector | ivec2/ivec3/ivec4 | Among themi Represents the vector type, and the number represents the number of components of the vector |
Floating point vector | vec2/vec3/vec4 | By default, yesfloat The number represents the number of components of a vector |
Floating point matrix | mat2/mat3/mat4 | The number represents the number of columns in the matrix, and the number of rows is the same as the number of columns |
2D texture | sampler2D | 2D textures, only available as uniform variables |
The texture is Cubemap | samplerCube | Cube texture can only be a uniform variable |
The structure of the body | struct | Similar to C constructs that aggregate variables together |
An array of | array | GLSL supports only 1-dimensional arrays, and the data types can be scalar, vector, matrix, or struct |
Vector constructors can be constructed in two ways:
- Single scalar parameter: All components of a vector are initialized to this scalar value.
- Multiple scalar parameters, vector parameters, or a mixture of scalar and vector parameters: Initialize all components of a vector in parameter order, ensuring that the number of parameters (the components of the vector parameters are split) is not less than the number of components of the vector.
vec4 aVec4 = vec4(1.0.1.0.1.0.1.0);
// All components are 1.0
vec4 bVec4 = vec4(1.0);
vec3 aVec3 = vec3(1.0);
// Initialize 4-dimensional vectors with vectors and scalars
vec4 cVec4 = vec4(aVec3, 1.0);
Copy the code
Type conversion: GLSL does not support implicit type conversion and must perform explicit type conversion. Vectors also support direct type conversion. That is, variables can only be assigned or operated on if their types are the same.
float floatParam = 1.0;
// float -> bool
bool boolParam = bool(floatParam);
vec4 fVec4 = vec4(1.0.1.0.1.0.1.0);
// 4 dimensional float vector -> 4 dimensional int vector
ivec4 iVec4 = ivec4(fVec4);
// 4 dimensional float vector -> 3 dimensional int vector
ivec3 iVec3 = ivec3(fVec4);
Copy the code
Matrix constructors also have two parameter constructs:
- Single scalar argument: used to initialize components on the main diagonal, all other components are 0.0.
- Multiple scalar parameters, vector parameters, or a mixture of scalar and vector parameters: Initialize all components of the matrix in the order of the parameters (column preference), ensuring that the number of parameters (component splitting of vector parameters) is not less than the number of matrix components.
// Assign values to the components of a matrix through multiple scalars
mat3 aMat3 = mat3(1.0.0.0.0.0./ / the first column
0.0.1.0.0.0./ / the second column
0.0.0.0.1.0); / / the third column
// A single scalar is used to initialize the components on the main diagonal; all other components are 0.0
mat3 bMat3 = mat3(1.0);
vec3 aVec3 = vec3(1.0.0.0.0.0);
vec3 bVec3 = vec3(0.0.1.0.0.0);
mat3 cMat3 = mat3(aVec3, // Initialize the first column with a vector
bVec3, // Initialize the second column with a vector
0.0.0.0.1.0); // Initialize the third column with multiple scalars
Copy the code
Vector and matrix operations
Vectors and matrices are made up of components, and we can access components in a variety of ways. For vectors, you can pass. And array subscripts can also be accessed through xyZW, RGBA, or STRQ, where xyZW is usually used for position-dependent vectors, RGBA is usually used for color-dependent vectors, and STRQ is usually used for texture coordinate dependent vectors. X, r, and S represent the first component of the vector. The above three methods should not be mixed. For example, XGR is not allowed.
A matrix can be regarded as a combination of vectors, and a MAT3 can be regarded as three VEC3. Therefore, vectors of a certain column can be obtained by array subscript, and then vector components can be accessed by the above method.
// Vector access
vec3 aVec3 = vec3(0.0.1.0.2.0);
vec3 temp;
temp = aVec3.xyz; // temp = {0.0, 1.0, 2.0}
temp = aVec3.xxx; // temp = {0.0, 0.0, 0.0}
temp = aVec3.zyx; // temp = {2.0, 1.0, 0.0}
// Matrix access
mat4 aMat4 = mat4(1.0);
vec4 column0 = aMat4[0]; // column0 = {1.0, 0.0,0.0,0.0}
float column1_row1 = aMat4[1] [1]; / / column1_row1 = 1.0
float column2_row2 = myMat4[2].z; / / column2_row2 = 1.0
Copy the code
The structure of the body
Similar to C, GLSL supports defining structures and automatically creates constructors (with the same name as structures) for structures that can be used to generate instances of structures.
// Leon is the new structure type. Leon is the structure variable and is optional.
struct Leon {
vec4 aVec4;
mat4 bMat4;
float cF;
} leon;
// Initialize the structure parameters through the structure constructor. The constructor parameters must have an exact correspondence with the elements of the structure
leon = Leon(vec4(1.0),mat4(1.0),1.0);
// Access a member variable through the. Operator
vec4 dVec4 = leon.aVec4;
mat4 eMat4 = leon.bMat4;
Copy the code
An array of
Like C, GLSL supports the definition of arrays, which can be any primitive or struct type. GLSL is special in two ways:
- In addition to
uniform
In addition to variables, the index of the array must be a compile-time constant. - Arrays are defined and initialized separately, that is, each element in the array must be initialized one by one after the array is defined, and the array cannot use a const qualifier.
// Define an array
float fArray[2];
vec2 vec2Array[2];
mat2 mat2Array[2];
Leon leonArray[2];
// Array elements must be initialized one by one
fArray[0] = 0.0;
fArray[1] = 1.0;
vec2Array[0] = vec2(0.0);
vec2Array[1] = vec2(1.0);
mat2Array[0] = mat2(0.0);
mat2Array[1] = mat2(1.0);
leonArray[0] = Leon(vec4(1.0),mat4(1.0),1.0);
leonArray[1] = Leon(vec4(1.0),mat4(1.0),1.0);
Copy the code
statements
Flow control statement
Flow control statements are very similar to C.
Looping statements
GLSL supports skipping a single loop with continue and exiting the entire loop with break.
// Loop controlled by counter
for(int i = 0; i <= 99; i++) {
function();
}
// Loop controlled by preconditions
int i = 0;
while(i <= 99) {
function();
i++;
}
// Loop controlled by post (loop) condition
do {
function();
i++;
} while(i <= 99);
Copy the code
Conditional statements
Similar to THE C language
if(condition){
functionA();
} else {
functionB();
}
Copy the code
This statement
The discard keyword is commonly used in slice shaders to discard the current slice, that is, to immediately exit the shader of the current slice, which ends up being the default color.
Start the statement
// Main is a vertex and slice shader entry, equivalent to C's main function
void main(void) {
function();
}
Copy the code
The operator
The GLSL operator is similar to C and will not be described here, except for the differences:
- GLSL requires that the variables on both sides of the operator have the same data type.
- For binary operators (*, /, +, -), the operands must be floating-point or integer.
- Comparison operators can only be used with scalars, and there are built-in functions for vector comparisons, which will be described later.
qualifiers
Storage qualifier
When declaring variables, you can modify them with storage qualifiers, similar to specifiers in C.
const
Const is used to modify compile-time constants (initial values must be assigned when declared), or read-only function arguments. Structure members cannot be declared as constants, but structure variables can be declared as constants and need to be initialized using the constructor at initialization time.
attribute
The attribute variable is the per-vertex data transmitted by the application to the vertex shader. That is, each vertex requires a copy of the data, which is usually used to represent vertex coordinates, vertex colors, texture coordinates, and other data. The attribute variable is read-only in the shader and cannot be modified in the vertex shader. In addition, the Attribute variable must be assigned by transferring data from the application executing the shader.
The maximum number of attributes that can be used is capped, and GL_MAX_VERTEX_ATTRIBS can be queried using the built-in function glGetIntegerv. OpenGL ES 2.0 supports at least eight attribute variables.
uniform
Uniform is available in vertex and fragment shaders to modify global variables, meaning they are not limited to a vertex or a pixel. Usually used to represent transformation matrix, texture and other data. Uniform variables are read-only in the shader and cannot be modified in the shader. In addition, uniform variables must be assigned by transferring data from the application executing the shader.
Shaders have a limited number of uniform usages. You can use the built-in glGetIntegerv function to query GL_MAX_VERTEX_UNIFORM_VECTORS and GL_MAX_FRAGMENT_UNIFORM_VECTORS. OpenGL ES 2.0 supports at least 128 vertex Uniform and 16 slice Uniform.
varying
Varying is used to declare the variables shared between the vertex shader and the slice shader. The vertex and fragment shaders must have the same VARYING variable declarations. The vertex shader first assigns a value to the varying variables of each vertex. The rasterization phase interpolates the varying variables (each of the rasterized shards gets a corresponding VARYING variable value). The interpolation results are then handed over to the shard shader for shading. Varying can only be used to modify floating-point scalars, floating-point vectors, floating-point matrices, and arrays containing these types.
The number of varying is also limited. GlGetIntegerv can be used to query GL_MAX_VARYING_VECTORS. OpenGL ES 2.0 supports at least eight varying variables.
Local variables and function parameters can only use the const qualifier. Function return values and structure members cannot use the qualifier. Attribute and UNIFORM variables cannot be assigned at initialization; they must be actively assigned by the application.
Parameter qualifier
GLSL provides parameter qualifiers that modify function parameters to indicate whether they are readable or not.
In (read-only parameter)
In is the default modifier, indicating that the parameter is passed by value and cannot be modified within a function.
Out (write parameters only)
Out indicates that the parameter is passed by reference, but the parameter is not initialized, so it is not readable within the function, only writable, and the modification will still take effect after the function ends.
Inout (read-write parameters)
Inout indicates that parameters are passed by reference and can be read and written within a function. And the changes still take effect after the function ends (similar to references in C++).
int newFunction(in bvec4 aBvec4, // read-only
out vec3 aVec3, // write-only
inout int aInt); // read-write
Copy the code
Precision qualifier
The precision qualifier specifies the range of precision to be used for shader variables, including lowp, mediump, and highp. When using low precision, OpenGL ES can run shaders more quickly and with low power consumption. The efficiency is improved due to the abandonment of precision. If the precision is not reasonable, the results of shader operation will appear distortion. So you need to test different precision to determine the most appropriate configuration.
Precision qualifier | describe |
---|---|
highp | The highest accuracy |
lowp | The minimum accuracy |
mediump | Intermediate accuracy, somewhere in between |
Precision qualifiers can modify integers or floating-point scalars, vectors, and matrices. In vertex shaders, the precision qualifier is optional; if no qualifier is specified, the highest precision is used by default. In a chip shader, the precision qualifier is required, either by specifying the precision directly when defining a variable or by specifying the default precision for the type.
// Specifies the precision for the type. If float is defined without a precision qualifier, highp is the default
precision highp float;
precision mediump int;
// Specify the precision for the variable
highp vec4 position;
varying lowp vec4 color;
Copy the code
In OpenGL ES, the definition and scope of precision depends on the implementation and is not completely consistent. The precision qualifier specifies the minimum range and precision that must be satisfied to store these variables. Implementations may use more scope and precision than required, but never less than required.
The range and precision of different precision qualifiers supported by different shaders can be queried by the following functions:
void GL_APIENTRY glGetShaderPrecisionFormat (GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision);
Copy the code
Where shaderType must be VERTEX_SHADER or FRAGMENT_SHADER; Precisiontype must be GL_LOW_FLOAT, GL_MEDIUM_FLOAT, GL_HIGH_FLOAT, GL_LOW_INT, GL_MEDIUM_INT, or GL_HIGH_INT; Range is a pointer to an array of integers of length 2, representing a range of values:
range[0] = log2(|min|)
range[1] = log2(|max|)
Copy the code
Precision is a pointer to an integer that is the corresponding number of precision digits (log2).
When there are more than one precision in an expression, select the one with the highest precision. When none of the precision is found, the default or maximum precision is used.
The order of qualifiers
When there are multiple qualifiers, there is a certain order to follow:
- General variables: Storage qualifier -> precision qualifier
- Function parameters: storage qualifier -> parameter qualifier -> precision qualifier
/ / variable
varying highp float color; // storage -> precision
void fun(const in lowp float size){ // storage -> parameter -> precision
}
Copy the code
pretreatment
Preprocessing instructions in GLSL are similar to C in that they start with # and each instruction occupies a single line. Common preprocessing instructions are as follows:
// Define and undefine
#define
#undef
// Conditional judgment
#if
#ifdef
#ifndef
#else
#elif
#endif
#pragma
#extension
#version
#line
Copy the code
Pragma represents compilation directives that control compiler behavior.
#pragma debug(on)
#pragma debug(off)
Copy the code
During development and debugging, you can enable the debug option to obtain more debugging information. The default value is off.
#version specifies which VERSION of the GLSL compiler to use. It must be written at the top of the compilation unit. It can only be preceded by comments or whitespace, and no other characters.
Each graphics card driver vendor can define its own OpenGL extension, such as GL_OES_EGL_image_external. The command to enable the extension is as follows:
// Set the behavior for an extension
#extension extension_name: behavior
// Set the behavior for all extensions
#extension all : behavior
// Enable OES textures
#extension GL_OES_EGL_image_external : require
Copy the code
Extension_name indicates an extension, all indicates all extensions supported by the compiler, and behavior indicates the operation on the extension, such as enabling or disabling the extension, as shown in the following:
behavior | describe |
---|---|
require | If an extension is enabled, an error is reported if the extension parameter isall , is bound to make a mistake |
enable | Enable an extension, warning if it is not supported, if the extension parameter isall , is bound to make a mistake |
warn | Unless the extension is required by another enabled extension, a warning will be issued if the extension parameter isall , a warning must be thrown |
disable | Disables an extension that throws an error if used, if the extension argument isall (default), no extensions are allowed |
For each supported extension, there is a corresponding macro definition that we can use to determine whether the compiler supports the extension.
#ifdef OES_extension_name
#extension OES_extension_name : enable
#else
#endif
Copy the code
In addition, there are some predefined system variables:
__LINE__ // int, the line number of the current source.
__FILE__ // int, the unique ID of the current Source String
__VERSION__ // Int, current GLSL version, e.g. 100 (100 = v1.00)
GL_ES // If the current environment is OpenGL ES, 1, otherwise 0
Copy the code
Built-in variables
The OpenGL shader language contains some built-in variables, which are mainly introduced here for vertex and slice shaders.
Vertex shader built-in variable
gl_Position
Gl_Position is the output variable that holds the homogeneous coordinates of the vertex positions. This value is used for primitive assembly, clipping, and other fixed pipe operations. If gl_Position is not assigned in the vertex shader, its value is uncertain in subsequent phases. Gl_Position can be written more than once, with the last value being written in subsequent steps.
gl_PointSize
Gl_PointSize is the output variable used by shaders to control the size of rasterized points, in pixels. If gl_PointSize is not assigned in the vertex shader, its value is indeterminate in subsequent phases.
Chip shader built-in variable
gl_FragColor
Gl_FragColor is the output variable that defines the color value of the chip in the subsequent pipeline. Gl_FragColor can be written multiple times, and the next step is based on the last written value. If the discard operation is performed, the slice is discarded and the gl_FragColor is no longer meaningful.
gl_FragCoord
Gl_FragCoord is a read-only variable, which saves the window coordinates of the current chip (x, Y, Z, 1/ W). This value is calculated by interpolation of the pixel during the pixel assembly stage. The Z-component represents the depth value of the current chip.
gl_FragDepth
Gl_FragDepth is an output variable used to change the chip depth value (instead of the gl_fragcoord.z depth value). If its value is written anywhere, it must be written to all execution paths, or its value may be ambiguous on unwritten paths.
gl_FrontFacing
Gl_FrontFacing is a read-only variable that has a value of true if the tile belongs to a face-forward tile. This variable can take one of the two colors calculated by the vertex shader to simulate double-sided lighting.
gl_PointCoord
Gl_PointCoord is a read-only variable that represents the two-dimensional coordinates of the current slice in the point pixel, ranging from 0.0 to 1.0. If the current primitive is not a point, the value read by gl_PointCoord will be ambiguous.
function
Custom function
GLSL supports custom functions, but functions cannot be nested, recursive calls are not supported, and the function return value type must be declared (void if there is no return value). If a function is called before it is defined, the function prototype needs to be declared.
vec4 getPosition(){
vec4 v4 = vec4(0..0..0..1.);
return v4;
}
Copy the code
Inline function
Triangular function
ParamType can be float, vec2, vec3, or vec4. The parameter type is the same as the return type.
The function prototype | describe |
---|---|
ParamType radians(ParamType degrees) | Convert the Angle to radians |
ParamType degrees(ParamType radians) | Convert radians to degrees |
ParamType sin(ParamType radians) | Calculate the sine in radians |
ParamType cos(ParamType radians) | Calculate the cosine in radians |
ParamType tan(ParamType radians) | Calculate the tangent in radians |
ParamType asin(ParamType value) | PI /2, PI /2, PI /2, PI /2 |
ParamType acos(ParamType value) | The inverse of the cosine evaluates the radian of the given value, the absolute value of value <= 1, and the range of radians returned is [0,π]. |
ParamType atan(ParamType y_over_x) | The inverse function of tan, which evaluates radians of a given value, returns radians in the range – PI over 2, PI over 2. |
ParamType atan(ParamType y, ParamType x) | The inverse function of tan, also called atan2, returns a tangent of y over x radians, and the x and y signs are used to determine which quadrant the Angle is in. The range of radians returned is (−π,π). If x and y are both 0, the result is undefined |
Exponential function
ParamType can be float, vec2, vec3, or vec4. The parameter type is the same as the return type.
The function prototype | describe |
---|---|
ParamType pow(ParamType x, ParamType y) | The power function returns x to the y power |
ParamType exp(ParamType x) | The exp function returns the constant e to the x |
ParamType exp2(ParamType x) | The exp2 function returns the constant 2 to the x power |
ParamType log(ParamType x) | Log base e of x |
ParamType log2(ParamType x) | Log base 2 of x |
ParamType sqrt(ParamType x) | Return the square root of X |
ParamType inversesqrt(ParamType x) | Returns the reciprocal of the square root of x |
The generic function
ParamType can be float, vec2, vec3, or vec4. The parameter type is the same as the return type.
The function prototype | describe |
---|---|
ParamType abs(ParamType x) | Return the absolute value of x |
ParamType sign(ParamType x) | Returns 1.0 if x is positive, 0.0 if x is zero, and -1.0 if x is negative |
ParamType floor(ParamType x) | Returns the largest integer less than or equal to x |
ParamType ceil(ParamType x) | Returns the minimum value greater than or equal to x |
ParamType fract(ParamType x) | Returns the fractional part of x, that is: x-floor (x). |
ParamType mod(ParamType x, ParamType y) | X — y * floor(x/y), if x and y are integers, returns the remainder of x divided by y |
ParamType mod(ParamType x, float y) | Variant of the mod above: y is always float, and for floating-point vectors, each component of the vector is divided by y |
ParamType min(ParamType x, ParamType y) | Returns the smaller values of two arguments. For floating-point vectors, operations are compared by component |
ParamType min(ParamType x, float y) | Variant of min above: y is always float, and for floating-point vectors, each component of the vector is compared to Y |
ParamType max(ParamType x, ParamType y) | Returns the larger value of both arguments. For floating-point vectors, operations are compared by component |
ParamType max(ParamType x, float y) | Variant of Max above: y is always float, and for floating-point vectors, each component of the vector is compared to Y |
ParamType clamp(ParamType x, ParamType minVal, ParamType maxVal) | If x is greater than minVal and less than maxVal, x is returned. If x is less than minVal, minVal is returned. If x is greater than maxVal, maxVal is returned |
ParamType clamp(ParamType x, float minVal, float maxVal) | Clamp variants above, minVal and maxVal are always float, and for floating-point vectors, each component of the vector is compared to minVal and maxVal |
ParamType mix(ParamType x, ParamType y, ParamType a) | Returns a linear mixture of x and y, i.ex * (1 - a) + y * a |
ParamType mix(ParamType x, ParamType y, float a) | In the variation of Mix above, A is always float, and for floating-point vectors, each component of the vector evaluates with A |
ParamType step(ParamType edge, ParamType x) | If x is less than edge, 0.0 is returned, otherwise 1.0 is returned |
ParamType step(float edge, ParamType x) | A variant of step above, Edge is always float, and for floating-point vectors, each component of the vector is computed with edge |
ParamType smoothstep(ParamType edge0, ParamType edge1, ParamType x) | If x is less than edge0, 0.0 is returned; If x is greater than edge1, 1.0 is returned. Otherwise, the returned value will be interpolated between 0.0 and 1.0 using Hermite polynomials |
ParamType smoothstep(float edge0, float edge1, ParamType x) | Variants of the above smoothstep, edge0 and EDge1 are always float, and for floating-point vectors, each component of the vector is compared to edge0 and EDge1 |
Geometric function
ParamType can be float, vec2, vec3, or vec4.
The function prototype | describe |
---|---|
float length(ParamType x) | Returns the vector length, the square root of the sum of squares of its components, or its absolute value for a floating-point scalar |
float distance(ParamType p0, ParamType p1) | Returns the distance between two points, which is the length of vector d(p0-P1, starting at p1 and pointing to P0), or its absolute value for a floating-point scalar |
float distance(ParamType p0, ParamType p1) | Returns the distance between two points, which is the length of vector d(p0-P1, starting at p1 and pointing to P0), or its absolute value for a floating-point scalar |
float dot(ParamType x, ParamType y) | Returns the dot product of two vectors, the sum of the products of their components, or the product of x and y for floating-point scalars |
vec3 cross(vec3 x, vec3 y) | Returns the cross product of two vectors, better known as a normal vector, perpendicular to the plane of the x and y vectors and whose length is equal to the area of the parallelogram of x and y. The input parameter can only be a three-component floating-point vector |
ParamType normalize(ParamType x) | Returns the unit vector of vector x, i.ex / \|x\| For floating-point scalars, return 1.0 directly |
ParamType faceforward(ParamType N, ParamType I, ParamType Nref) | If dot(Nref, I) < 0 then return the N vector, otherwise return the -n vector |
ParamType reflect(ParamType I, ParamType N) | I: the incident vector, N: the normal vector of the reflecting surface, reflecting direction: I minus 2 dot(N,I) times N, which is usually the unit vector |
ParamType refract(ParamType I, ParamType N, float eta) | I: the incident vector(incident vector), N: the normal vector of the refracting surface(refracting normal vector), ETA: refractive index. Returns the refraction vector of incident vector I with respect to normal vector N, with refractive index eta. I and N are generally unit vectors |
Matrix function
Instead of traditional vector multiplication, a matrixCompMult returns a vector whose components are equal to the product of the components of the x and y vectors.
mat2 matrixCompMult(mat2 x, mat2 y)
mat3 matrixCompMult(mat3 x, mat3 y)
mat4 matrixCompMult(mat4 x, mat4 y)
// Result vector z
z[i][j] = x[i][j] * y[i][j]
Copy the code
Vector (vector) relation function
Vector (vector) relation functions mainly include: <, <=, >, >=, ==,! The function parameter is an integer or floating point vector, and the return value is a Boolean vector generated by comparing the components of the parameter vector. Bvec represents BVEC2, bVEC3, and bVEC4. Ivec indicates IVEC2, IVEC3, or IVEC4. Vec stands for VEC2, VEC3, and VEC4. The size of the argument vector and the return vector must be the same.
The function prototype | describe |
---|---|
bvec lessThan(vec x, vec y) bvec lessThan(ivec x, ivec y) |
Result [I] = x[I] < y[I] |
bvec lessThanEqual(vec x, vec y) bvec lessThanEqual(ivec x, ivec y) |
Result [I] = x[I] <= y[I] |
bvec greaterThan(vec x, vec y) bvec greaterThan(ivec x, ivec y) |
Result [I] = x[I] > y[I] |
bvec greaterThanEqual(vec x, vec y) bvec greaterThanEqual(ivec x, ivec y) |
Result [I] = x[I] >= y[I] |
bvec equal(vec x, vec y) bvec equal(ivec x, ivec y) |
Result [I] = x[I] == y[I] |
bvec notEqual(vec x, vec y) bvec notEqual(ivec x, ivec y) |
Result [I] = x[I]! = y[i] |
bool any(bvec x) | Returns true if either component of the argument vector is true |
bool all(bvec x) | Return true if all components of the argument vector are true |
bvec not(bvec x) | Take the inverse of the Boolean vector |
Texture lookup function
The purpose of texture query is to extract the color information of specified coordinates from texture. There are two types of textures in OpenGL:
- 2D textures (sampler2D)
- 3D texture (samplerCube)
Texture lookup functions can be used in both vertex shaders and fragment shaders. However, the level of detail is not computed in the vertex shader, so the texture lookup function is slightly different.
The following functions are only available in vertex shaders:
vec4 texture2DLod(sampler2D sampler, vec2 coord, float lod);
vec4 texture2DProjLod(sampler2D sampler, vec3 coord, float lod);
vec4 texture2DProjLod(sampler2D sampler, vec4 coord, float lod);
vec4 textureCubeLod(samplerCube sampler, vec3 coord, float lod);
Copy the code
The following functions are only available in the fragment shader:
vec4 texture2D(sampler2D sampler, vec2 coord, float bias);
vec4 texture2DProj(sampler2D sampler, vec3 coord, float bias);
vec4 texture2DProj(sampler2D sampler, vec4 coord, float bias);
vec4 textureCube(samplerCube sampler, vec3 coord, float bias);
Copy the code
The float type parameter BIAS represents the bias added after using Mipmaps to calculate the appropriate level of detail for the texture before performing the actual texture lookup operation.
The following functions are available in both vertex shaders and fragment shaders:
vec4 texture2D(sampler2D sampler, vec2 coord);
vec4 texture2DProj(sampler2D sampler, vec3 coord);
vec4 texture2DProj(sampler2D sampler, vec4 coord);
vec4 textureCube(samplerCube sampler, vec3 coord);
Copy the code