Лекция 6 (14.11.2013). Новая библиотека #include "glew.h Подключается перед #include "gl.h В версии 3.0 2 вида шейдеров:

Презентация:



Advertisements
Похожие презентации
© Luxoft Training 2013 Annotations. © Luxoft Training 2013 Java reflection / RTTI // given the name of a class, get a "Class" object that // has all info.
Advertisements

1/27 Chapter 9: Template Functions And Template Classes.
Loader Design Options Linkage Editors Dynamic Linking Bootstrap Loaders.
Unit II Constructor Cont… Destructor Default constructor.
Multiples Michael Marchenko. Definition In mathematics, a multiple is the product of any quantity and an integer. in other words, for the quantities a.
HPC Pipelining Parallelism is achieved by starting to execute one instruction before the previous one is finished. The simplest kind overlaps the execution.
Linear Block Codes Mahdi Barhoush Mohammad Hanaysheh.
Conditional Statements. Program control statements modify the order of statement execution. Statements in a C program normally executes from top to bottom,
© 2009 Avaya Inc. All rights reserved.1 Chapter Two, Voic Pro Components Module Two – Actions, Variables & Conditions.
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Route Selection Using Policy Controls Applying Route-Maps as BGP Filters.
Date: File:GRAPH_02e.1 SIMATIC S7 Siemens AG All rights reserved. SITRAIN Training for Automation and Drives Project Planning and Configuration.
Michael Marchenko. In mathematics, a sequence is an ordered list of objects (or events). Like a set, it contains members (also called elements, or terms),
S4-1 PAT328, Section 4, September 2004 Copyright 2004 MSC.Software Corporation SECTION 4 FIELD IMPORT AND EXPORT.
Sequences Sequences are patterns. Each pattern or number in a sequence is called a term. The number at the start is called the first term. The term-to-term.
Data Types in C. A Data Type A data type is –A set of values AND –A set of operations on those values A data type is used to –Identify the type of a variable.
Operator Overloading Customised behaviour of operators Chapter: 08 Lecture: 26 & 27 Date:
Inner Classes. 2 Simple Uses of Inner Classes Inner classes are classes defined within other classes The class that includes the inner class is called.
© 2009 Avaya Inc. All rights reserved.1 Chapter Seven, Customer Call Reporter (CCR) Module Two – Standard Configuration.
Loops Objectives Students will: 1. Explain what a loop is and describe the three main types of loops used in programming. 1. Дать понятие циклам. И объяснить.
1/30 Chapter 8: Dynamic Binding And Abstract classes.
Транксрипт:

Лекция 6 ( )

Новая библиотека #include "glew.h Подключается перед #include "gl.h В версии вида шейдеров: Вершинный, фрагментный В версии видов шейдеров: Вершинный, фрагментный, геометрический, мозаичный контрольный, мозаичный исполнительный

Заголовок Секция кода Секция данных Таблица импорта Таблица экспорта (для dll) Секция ресурсов Таблица реллокаций Дополнительные секции (от упаковщиков…)

вершинные шейдеры и фрагментные шейдеры Обработка вершин включает в себя операции, выполняемые над каждой вершиной, в основном это преобразование и настройка освещения. Фрагменты это структуры данных для каждого пиксела,­ которые создаются в результате растеризации графических примитивов.

· Язык шейдеров OpenGL высокоуровневый процедурный язык. · Такой же язык, с небольшими изменениями, используется для вершинных ­и фрагментных шейдеров. · Он базируется на синтаксисе и управлении C и С++. · Изначально в нем поддерживаются векторные и матричные операции, так как они являются неотъемлемой частью многих графических алгоритмов. · Язык более жестко проверяет типы, чем C и C++, и функции могут вызываться по возвращаемому значению. · Он использует квалификаторы типов чаще, чем управление вводом-выводом. · У него нет ни ограничений на длину шейдера, ни необходимости ее запрашивать.

увеличенная реалистичность отображения материалов металла, камня, дерева, краски и т. д.; · увеличенная реалистичность эффектов освещения освещенных областей, мягких теней и т. д.; · изображение природных явлений огня, дыма, воды, облаков и т. д.; · создание не фотографически точных изображений имитация живописи, рисунка пером, воспроизведение техники иллюстрации и т. д.; · использование текстур для хранения нормалей, блеска, полиномных коэффициентов и т. д. новые возможности использования текстурной памяти; · меньшее количество способов доступа к текстурам текстуры могут быть созданы с помощью процедур, а не посредством доступа к текстурным картам, хранящимся в текстурной памяти; · использование новых способов обработки изображений искривления, нечеткой обработки маски, сложного сглаживания и т. д.; · создание эффектов анимации интерполяции ключевого кадра, процедурно определенных движений; · использование программируемых методов антиалиасинга.

программируемый модуль, который выполняет операции над входными значениями вершин и другими связанными с ними данными. Вершинный процессор предназначен для выполнения следующих традиционных операций с графикой: · преобразования вершин; · преобразования нормали, нормализации; · генерирования текстурных координат; · преобразования текстурных координат; · настройки освещения; · наложения цвета материала.

программируемый модуль, который выполняет операции над фрагментами и другими связанными с ними данными. Фрагментный процессор может выполнять следующие стандартные графические операции: · операции над интерполированными значениями; · доступ к текстурам; · наложение текстур; · создание эффекта дымки; · наложение цветов.

#include "glew.h" #include "glut.h" #include "GL/gl.h" #include "GL/glu.h" #include "glaux.h" int main() { // Инициализация OpenGL glewInit(); // Инициализация шейдеров glutMainLoop(); }

GLuint glCreateShader(GLenum type); Allocates a shader object, type must be either GL_VERTEX_SHADER or GL_FRAGMENT_SHADER. The return value is eitner a non-zero integer or zero, if an error occurred.

void glShaderSource(GLuint shader, GLsizei count, const GLchar **string, const GLint * lengthy. Associates the source of a shader with a shader object shader, string is an array of count GLchar strings that compose the shaders source. The character strings in string may be optionally null- terminated, length can be one of three values. If length is NULL, then its assumed that each string provided in string is null-terminated. Otherwise, length has count elements, each of which specifies the length of the corresponding entry in string. If the value of an element in the array length is a positive integer, the value represents the number of characters in the corresponding string element. If the value is negative for particular elements, then that entry in string is assumed to be null-terminated.

void glCompileShader(GLuint shader); Compiles the source code for shader. The results of the compilation can be queried by calling glGetShaderiv() with an argument of GL_COMPILE_ STATUS.

void glGetShaderInfoLog(GL uint shader, GLsizei bufSize, GLsizei *length, char *infoLog); Returns the log associated with the last compilation of a shader object. shader specifies which shader object to query The log is returned as a null-terminated character string of length characters in the buffer infoLog. The maximum return size of the log is specified in bufSize. If length is NULL, then no string was returned.

GLuint glCreateProgram(); Allocates a shader program. void glAttachShader(GLuint program, GLuint shader); Associates the shader object, shader, with the shader program, program. A shader object can be attached to a shader program at any time, although its functionality will only be available after a successful link of the shader program. A shader object can be attached to multiple shader programs simultaneously.

void glDetachShader(GLuint program, GLuint shader); Removes the association of a shader object, shader, from the shader program, program. If shader is detached from program and has been marked for deletion (by calling glDeleteShaderQ), it is deleted at that time.

void glLinkProgram(GLuint program); Processes all shader objects attached to program to generate a completed shader program. The result of the linking operation can be queried by calling glGetProgramiv() with GL_LINK_STATUS. GL_TRUE is returned for a successful link; GL_FALSE is returned otherwise. As with shader objects, theres a chance that the linking phase may fail due to errors in the attached shader objects. You can query the result of the link operations success by calling glGetProgramiv() with an argument of GL_ LINK_STATUS. If GL_TRUE was returned, the link was successful, and youre able to specify the shader program for use in processing vertices or fragments. If the link failed, represented by GL_FALSE being returned, then you can determine the cause of the failure by retrieving the program link information log by calling glGetProgramLog().

void glUseProgram(GLuint program); Uses program for either vertex or fragment processing, depending upon the type of shader created with glCreateShader(). If program is zero, no shader is used for processing and OpenGL reverts to fixed- function operation.

void glDeleteShader(GLuint shader); Deletes shader. If shader is currently linked to one or more active shader programs, the object is tagged for deletion and deleted once the shader program is no longer being used by any shader piogram. void glDeleteProgram( GLuint program); Deletes program immediately if not currently in use in any context, or tagged for deletion when the program is no longer in use by any contexts.

GLboolean glIsProgram(GLuint program); Returns GL_TRUE if program is the name of a shader program. If program is zero, or non- zero and not the name of a shader object, GL_FALSE is returned. GLboolean glIsShader(GLuint shader); Returns GL_TRUE if shader is the name of a shader object. If shader is zero, or non-zero and not the name of a shader object, GL_FALSF is returned.

void gl Validate Program(GLuint program); Validates program against the current OpenGL state settings. After validation, the value of GL_VALIDATE_STATUS will be set to either GL_ TRUE, indicating that the program will execute in the current OpenGL environment, or GL_FALSE otherwise. The value of GL._VALIDATE_ STATUS status can be queried by calling glGetProgramiv().

vec2, vec3, vec4 - 2D, 3D and 4D floating point vector ivec2, ivec3, ivec4 - 2D, 3D and 4D integer vector bvec2, bvec3, bvec4 - 2D, 3D and 4D boolean vectors For floats here are also matrix types: mat2, mat3, mat4 - 2x2, 3x3, 4x4 floating point matrix sampler1D, sampler2D, sampler3D - 1D, 2D and 3D texture samplerCube - Cube Map texture sampler1Dshadow, sampler2Dshadow - 1D and 2D depth-component texture

gl_Vertex 4D vector representing the vertex position gl_Normal 3D vector representing the vertex normal gl_Color 4D vector representing the vertex color gl_MultiTexCoordX 4D vector representing the texture coordinate of texture unit X

gl_ModelViewMatrix 4x4 Matrix representing the model-view matrix. gl_ModelViewProjectionMatrix 4x4 Matrix representing the model-view-projection matrix. gl_NormalMatrix 3x3 Matrix representing the inverse transpose model-view matrix. This matrix is used for normal transformation.

gl_FrontColor 4D vector representing the primitives front color gl_BackColor 4D vector representing the primitives back color gl_TexCoord[X] 4D vector representing the Xth texture coordinate gl_Position 4D vector representing the final processed vertex position. Only available in vertex shader. gl_FragColor 4D vector representing the final color which is written in the frame buffer. Only available in fragment shader. gl_FragDepth float representing the depth which is written in the depth buffer. Only available in fragment shader.

void main() { gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; }

void main() { gl_FragColor = vec4(0.0, 0.5, 0.0, 1.0); }

uniform sampler2D my_color_texture; uniform mat4 my_texture_matrix; varying vec3 vertex_to_light_vector; varying vec3 vertex_to_eye_vector; attribute vec3 tangent; attribute vec3 binormal;

GLint glGetUniformLocationARB(GLhandleARB program, const GLcharARB * name) void glUniform{1|2|3|4}{f|i}ARB(GLint location, TYPE val) void glUniform{1|2|3|4}{f|i}vARB(GLint location, GLuint count, const TYPE * vals) void glUniformMatrix{2|3|4|}fvARB(GLint location, GLuint count, GLboolean transpose, const GLfloat * vals)

GLint glGetAttribLocationARB(GLhandleARB program, const GLcharARB* name) void glVertexAttrib{1|2|3|4}{s|f|d}ARB(GLuint index, TYPE val) void glVertexAttrib{1|2|3|4}{s|f|d}vARB(GLuint index, const TYPE * vals)

HRSRC WINAPI FindResource( _In_opt_ HMODULE hModule, _In_ LPCTSTR lpName, _In_ LPCTSTR lpType ); Типы ресурсов: us/library/windows/desktop/ms648009%28v= vs.85%29.aspx us/library/windows/desktop/ms648009%28v= vs.85%29.aspx

HGLOBAL WINAPI LoadResource( _In_opt_ HMODULE hModule, _In_ HRSRC hResInfo ); LPVOID WINAPI LockResource( _In_ HGLOBAL hResData ); DWORD WINAPI SizeofResource( _In_opt_ HMODULE hModule, _In_ HRSRC hResInfo );

Microsoft Visual Studio Вид – Ресурсы – Щелчок правой кнопкой мыши – Добавить – Ресурс – HTML Узнать номер ресурса: Вид – Ресурсы – Щелчок правой кнопкой мыши – Символы ресурсов