Orientation du cours - FIL Lille 1aubert/m3ds/m3ds_intro... · 2019. 1. 13. · les frameworks GUI...

11
Chapitre 1 : Introduction - Programmation 3D Modélisation 3D et Synthèse Fabrice Aubert [email protected] Master Informatique 2018-2019 F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 1/66 1 Objectifs de M3DS F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 2/66 Fondations d’une application 3D Modélisation 3D : représentation et construction informatique des objets 3D (forme, position). Visualisation 3D : rendu projectif et par lancer de rayons, éclairage, texture. Interaction 3D : navigation/sélection/manipulation. Animation 3D : représentation et algorithme du mouvement. Programmation 3D : développement/réalisation. On commencera par de la programmation 3D (comment tracer ?). F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 3/66 Orientation du cours Approche "bas-niveau" du développement 3D pour acquérir les fondements : Eléments algébriques : coordonnées, repères, produit scalaire, ... (application informatique) Représentations et algorithmes fondamentaux : modèles 3D, élimination parties cachées, ... Librairie de programmation 3D : OpenGL. Nous n’utiliserons pas d’outils "haut-niveau" : Pas d’infographie : 3D Studio Max, Blender, Maya, Rhino 3D, ... Pas de Conception Assistée par Ordinateur (CAO) : SolidWorks, SolidEdge, CATIA, ... Pas d’utilisation de frameworks de développement 3D : Unity3D, jMonkeyEngine, Ogre3D, Open SceneGraph, Unreal Engine,... F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 4/66 Environnement TPs C++ 11 OpenGL (> 3.0) Qt Basé sur des squelettes à compléter F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 5/66 2 Introduction à OpenGL F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 6/66

Transcript of Orientation du cours - FIL Lille 1aubert/m3ds/m3ds_intro... · 2019. 1. 13. · les frameworks GUI...

Page 1: Orientation du cours - FIL Lille 1aubert/m3ds/m3ds_intro... · 2019. 1. 13. · les frameworks GUI "usuels" (Qt, GTK+, wxWidgets, ...) proposent de gérer une fenêtre/widget OpenGL.

Chapitre 1 : Introduction - Programmation 3DModélisation 3D et Synthèse

Fabrice Aubert

[email protected]

Master Informatique

2018-2019

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 1 / 66

1 Objectifs de M3DS

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 2 / 66

Fondations d’une application 3D

I Modélisation 3D : représentation et construction informatique des objets 3D (forme,position).

I Visualisation 3D : rendu projectif et par lancer de rayons, éclairage, texture.

I Interaction 3D : navigation/sélection/manipulation.

I Animation 3D : représentation et algorithme du mouvement.

I Programmation 3D : développement/réalisation.

I On commencera par de la programmation 3D (comment tracer?).

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 3 / 66

Orientation du cours

I Approche "bas-niveau" du développement 3D pour acquérir les fondements :

• Eléments algébriques : coordonnées, repères, produit scalaire, ... (applicationinformatique)

• Représentations et algorithmes fondamentaux : modèles 3D, élimination partiescachées, ...

• Librairie de programmation 3D : OpenGL.

I Nous n’utiliserons pas d’outils "haut-niveau" :

• Pas d’infographie : 3D Studio Max, Blender, Maya, Rhino 3D, ...• Pas de Conception Assistée par Ordinateur (CAO) : SolidWorks, SolidEdge, CATIA, ...• Pas d’utilisation de frameworks de développement 3D : Unity3D, jMonkeyEngine,

Ogre3D, Open SceneGraph, Unreal Engine,...

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 4 / 66

Environnement TPs

I C++ 11

I OpenGL (> 3.0)

I Qt

I Basé sur des squelettes à compléter

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 5 / 66

2 Introduction à OpenGL

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 6 / 66

Page 2: Orientation du cours - FIL Lille 1aubert/m3ds/m3ds_intro... · 2019. 1. 13. · les frameworks GUI "usuels" (Qt, GTK+, wxWidgets, ...) proposent de gérer une fenêtre/widget OpenGL.

OpenGL

I tracer des triangles...

I API de rendu 3D dédiée aux cartes graphiques.

I 2 librairies majeures sur desktop : OpenGL et Direct3D

I déclinaison sur mobile : OpenGL ES

I déclinaison pour le web : WebGL

I Spécifications définies par le consortium http ://www.khronos.org/

I Site officiel : http ://www.opengl.org/

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 7 / 66

Tutoriels OpenGL

I http ://www.arcsynthesis.org/gltut/

I http ://www.opengl-tutorial.org/

I http ://ogldev.atspace.co.uk/

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 8 / 66

Mise en place

I Initialisation d’un contexte OpenGL par le serveur graphique (Windows, X11, etc).

I Opération très bas-niveau⇒• les frameworks GUI "usuels" (Qt, GTK+, wxWidgets, ...) proposent de gérer une

fenêtre/widget OpenGL.• ou passer par une librairie dédiée (exemple : freeGlut).

I ⇒ les squelettes des tps utilisent le framework Qt (ouverture de la fenêtre OpenGL, etc,assuré par les squelettes).

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 9 / 66

Squelette des TP

I Mise en oeuvre usuelle (événementiel ; démarche similaire dans tous les frameworks) :

GLAppl icat ion : : GLAppl icat ion ( ) {/ / cons t ruc teu r => i n i t i a l i s a t i o n des données de l ’ a p p l i c a t i o n. . .

}

void GLAppl icat ion : : i n i t i a l i z e ( ) {/ / appelée 1 seule f o i s à l ’ i n i t i a l i s a t i o n du contexte OpenGL/ / => i n i t i a l i s a t i o n s concernant OpenGLg lC learCo lo r ( 1 , 1 , 1 , 1 ) ;/ / . . .

}

void GLAppl icat ion : : res i ze ( i n t width , i n t he igh t ) {/ / appelée à chaque dimensionnement du widget OpenGL/ / ( i n c l u s l ’ ouver ture de l a fenê t r e )/ / => r églages l i és à l a t a i l l e de l a fenê t r eg lV iewpor t (0 ,0 , width , he igh t ) ;/ / . . .

}

void GLAppl icat ion : : update ( ) {/ / appelée tou tes les 20ms (60Hz)/ / => met t re à j o u r les données de l ’ a p p l i c a t i o n/ / avant l ’ a f f i chage de l a prochaine image ( animat ion )/ / . . .

}

void GLAppl icat ion : : draw ( ) {/ / appelée après chaque update/ / => t r a c e r tou te l ’ imageg lC lea r (GL_COLOR_BUFFER_BIT ) ;/ / . . .

}

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 10 / 66

Premier exemple

I Se familiariser avec le vocabulaire technique de la prog3D• Vertex Buffer Object (VBO)• Vertex Array Object (VAO)• Program Shader (Vertex Shader et Fragment Shader).• Commandes de tracé.

I Suite du chapitre : très technique ! (CTD = principes/étapes/commentaires nécessaires ; TP= mise en pratique du code)

???======================⇒

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 11 / 66

Sommets des triangles

I On doit définir la position des 6 sommets des triangles (sommet = vertex en anglais).I Les coordonnées (x,y,z) en OpenGL sont normalisées : NDC = Normalized Device

Coordinates• x (horizontal), y (vertical) et z (profondeur) sont comprises dans [−1,1]

GLAppl icat ion . h :−−−−−−−−−−−−−−−−class GLAppl icat ion {

. . .GLAppl icat ion ( ) ;. . .

private :s td : : vector < f loa t > _pos i t ionData ;. . .

}

GLAppl icat ion . cpp :−−−−−−−−−−−−−−−−−−GLAppl icat ion : : GLAppl icat ion ( ) {

_pos i t ionData ={−0.8 ,0.0 ,−0.3 , / / ve r tex 0 / / f i r s t t r i a n g l e0.3 ,−0.7 ,−0.3 , / / ve r tex 10.0 ,0.9 ,−0.3 , / / ve r tex 20.4 ,−0.5 ,0.4 , / / ve r tex 3 / / second t r i a n g l e0 .9 ,0 .4 ,0 .4 , / / ve r tex 40.8 ,−0.9 ,0.4 / / ve r tex 5

} ;}

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 12 / 66

Page 3: Orientation du cours - FIL Lille 1aubert/m3ds/m3ds_intro... · 2019. 1. 13. · les frameworks GUI "usuels" (Qt, GTK+, wxWidgets, ...) proposent de gérer une fenêtre/widget OpenGL.

Copie sur le serveur OpenGL

I OpenGL manipule/trace des données qui sont dans sa propre mémoire (serveur OpenGL).

I Il faut donc copier les données de l’application cliente dans la mémoire OpenGL.

I ⇒ Utilisation des Vertex Buffer Objects (VBO).

I VBO = zone mémoire OpenGL identifiée par un entier.

GLAppl icat ion . h :−−−−−−−−−−−−−−−−class GLAppl icat ion {

. . .GLAppl icat ion ( ) ;void in i tVBO ( ) ;. . .

private :s td : : vector < f loa t > _pos i t ionData ;GLuint _ p o s i t i o n B u f f e r ; / / un i d e n t i f i a n t pour un VBO. . .

}

I Copie des données _positionData dans le VBO _positionBuffer (cf signification desinstructions dans transparent suivant) :

GLAppl icat ion . cpp :−−−−−−−−−−−−−−−−−−void GLAppl icat ion : : in i tVBO ( ) {

g lGenBuffers (1 ,& _ p o s i t i o n B u f f e r ) ;g lB indBu f fe r (GL_ARRAY_BUFFER, _ p o s i t i o n B u f f e r ) ;g lBu f fe rDa ta (GL_ARRAY_BUFFER, _pos i t ionData . s i ze ()∗ s i z e o f ( f l o a t ) , _pos i t ionData . data ( ) ,GL_STATIC_DRAW ) ;

}

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 13 / 66

VBO : Vertex Buffer Object

GLAppl icat ion . cpp :−−−−−−−−−−−−−−−−−−void GLAppl icat ion : : in i tVBO ( ) {

g lGenBuffers (1 ,& _ p o s i t i o n B u f f e r ) ;g lB indBu f fe r (GL_ARRAY_BUFFER, _ p o s i t i o n B u f f e r ) ;g lBu f fe rDa ta (GL_ARRAY_BUFFER, _pos i t ionData . s ize ()∗ s i z e o f ( f l o a t ) , _pos i t ionData . data ( ) ,GL_STATIC_DRAW ) ;

}

I glGenBuffers : génère un nouvel identifiant (c’est un entier) pour une zone mémoire OpenGL (unbuffer). L’identifiant _positionBuffer est encore appelé handle ou référence.

I glBindBuffer : indique quel est le VBO courant actif. Après ce bind, toutes les instructions quiconcernent ARRAY_BUFFER concerneront le VBO _positionBuffer (indirection).

I glBufferData : recopie les données clientes (contenues dans _positionData) dans le buffer OpenGLréférencé par ARRAY_BUFFER (ici l’identifiant _positionBuffer).

Syntaxe : void glBufferData(GLenum target, GLsizeiptr size, const GLvoid ∗data, GLenum usage);

I Remarque : le contenu des VBO n’a aucune interprétation particulière pour OpenGL ! (cesont des octets).

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 14 / 66

Résumé copie dans VBO 1/4

Client (Application C++)

-0.8 0.0 -0.3 0.3 -0.7 -0.3 0.0 ... _positionData

_positionBuffer

ARRAY_BUFFER

52

52

VBO 52

VBO 51

...

...

Serveur OpenGLClient (Application C++)

-0.8 0.0 -0.3 0.3 -0.7 -0.3 0.0 ... _positionData

ARRAY_BUFFER

VBO 52

VBO 51

...

...

Serveur OpenGL

I But : copier les données de _positionData dans un VBO.

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 15 / 66

Résumé copie dans VBO 2/4

I 1) Récupérer un identifiant d’un buffer disponible (parglGenBuffers(1,&_positionBuffer); sur l’exemple on suppose que cela donnel’identifiant 52).

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 16 / 66

Résumé copie dans VBO 3/4

I 2) Indiquer à OpenGL le buffer de travail courant (parglBindBuffer(GL_ARRAY_BUFFER,_positionBuffer);

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 17 / 66

Résumé copie dans VBO 4/4

I 3) Faire la copie des données dans le buffer de travail courant (parglBufferData(GL_ARRAY_BUFFER,...,_positionData.data(),...);

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 18 / 66

Page 4: Orientation du cours - FIL Lille 1aubert/m3ds/m3ds_intro... · 2019. 1. 13. · les frameworks GUI "usuels" (Qt, GTK+, wxWidgets, ...) proposent de gérer une fenêtre/widget OpenGL.

Commande de tracé

void GLAppl icat ion : : draw ( ) {g lC lea r (GL_COLOR_BUFFER_BIT ) ;

. . .glDrawArrays (GL_TRIANGLES, 0 , 6 ) ;. . .

}

I Tracer des triangles en prenant 6 sommets (0 = début = à partir du premier sommet).

I Cela ne suffit pas !

I Il faut préciser avant glDrawArrays où sont les données des sommets à tracer (rôle desVAO) et comment "afficher" (rôle des shaders).

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 19 / 66

Pipeline OpenGL (principe)

Etapes successives (= pipeline) lors du glDrawArrays :

Idem pour les triangles suivants.

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 20 / 66

Shaders

I Ce sont des programmes qu’il faut donner à OpenGL (sources, compilation, linkage).

I Langage : GLSL (GL Shading Language). Proche du C. Très orienté 3D (types prédéfinis,fonctions).

I Exemple de vertex shader simple (exécuté pour chaque sommet) :

# vers ion 130

i n vec3 p o s i t i o n ; / / un a t t r i b u t correspondant à ( x , y , z )

void main ( ) {g l _ P o s i t i o n =vec4 ( pos i t i on , 1 . 0 ) ;

}

I attribut position = données d’entrées pour chaque sommet. Il faudra indiquer à OpenGLcomment alimenter cet attribut (i.e. où aller chercher les valeurs de position).

I gl_Position = variable prédéfinie obligatoirement à affecter (objectif obligatoire du vertexshader = "calculer" la position du sommet).

I vec4 = 4 coordonnées? ? gl_Position est un vec4 (i.e. x,y,z et w) : coordonnéeshomogènes (décrites plus tard).

I Pour l’instant (on précisera au chapitre suivant) on prend w = 1.0 ; les coordonnées(x ,y ,z) de gl_Position sont à donner en NDC (Normalized Device Coordinates).

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 21 / 66

Fragment shader

I Exemple de fragment shader simple (exécuté pour chaque pixel affiché) :

# vers ion 130

out vec4 f ragCo lo r ; / / s o r t i e = données du p i x e l

void main ( ) {f ragCo lo r=vec4 ( 1 , 0 , 0 , 1 ) ; / / rouge , ver t , bleu , alpha

}

I obligatoire de donner au minimum une sortie (fragColor ici) qui sera la couleur du pixel.

I remarque : toutes les données associées à un pixel sont regroupées sous le nom defragment.

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 22 / 66

Shaders en OpenGL

Il faut :I Créer un identifiant pour un program shader : un program shader regroupera un vertex

shader et un fragment shader.

I Créer les identifiants pour le fragment et le vertex shader.

I Affecter les codes sources à ces identifiants.

I Compiler le fragment et le vertex shader.

I Linker le program shader.

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 23 / 66

Shaders en OpenGL

void GLAppl icat ion : : in i tProgramShader ( ) {s t r i n g vertexSource =

" # vers ion 130\n "" i n vec3 p o s i t i o n ; " / / " t r a d i t i o n n e l l e m e n t " : a t t r i b u t " p o s i t i o n " appelé " ver tex "" vo id main ( ) { "" g l _ P o s i t i o n =vec4 ( pos i t i on , 1 . 0 ) ; "" } " ;

s t r i n g fragmentSource =" # vers ion 130\n "" out vec4 f ragCo lo r ; "" vo id main ( ) { "" f ragCo lo r=vec4 ( 1 , 0 , 0 , 1 ) ; "" } " ;

_program=glCreateProgram ( ) ; / / membre GLuint _program ;

GLuint vertexShader=glCreateShader (GL_VERTEX_SHADER) ;GLuint fragmentShader=glCreateShader (GL_FRAGMENT_SHADER) ;glAt tachShader ( _program , vertexShader ) ;g lAt tachShader ( _program , fragmentShader ) ;

const char ∗source ;source=vertexSource . c_s t r ( ) ;glShaderSource ( vertexShader ,1 ,& source ,NULL ) ;source=fragmentSource . c_s t r ( ) ;glShaderSource ( fragmentShader ,1 ,& source ,NULL ) ;glCompileShader ( vertexShader ) ;glCompileShader ( fragmentShader ) ;

g l B i n d A t t r i b L o c a t i o n ( _program ,0 , " p o s i t i o n " ) ;

glLinkProgram ( _program ) ;}

I glBindAttribLocation??⇒ l’attribut position du vertex shader sera identifié par le numéro 0 (sera utilisé pouralimenter les valeurs de cet attribut position).

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 24 / 66

Page 5: Orientation du cours - FIL Lille 1aubert/m3ds/m3ds_intro... · 2019. 1. 13. · les frameworks GUI "usuels" (Qt, GTK+, wxWidgets, ...) proposent de gérer une fenêtre/widget OpenGL.

Tracé OpenGL

void GLAppl icat ion : : draw ( ) {/ / appelée après chaque update/ / => t r a c e r tou te l ’ image

g lC lea r (GL_COLOR_BUFFER_BIT ) ;

glUseProgram ( _program ) ;. . .glDrawArrays (GL_TRIANGLES, 0 , 6 ) ;

glUseProgram ( 0 ) ;. . .

}

I On a indiqué avec quel programme shader il faut tracer les triangles.

I glUseProgram(0)?? précaution pour d’éventuels effets de bord ("normalement" inutile).

I Cela ne suffit toujours pas !

I Il faut préciser où se trouvent les données des sommets, c’est-à-dire comment alimenterles attributs du vertex shader (i.e. sur cet exemple, indiquer où se trouvent les valeurs del’attribut position)⇒ rôle des VAO.

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 25 / 66

Vertex Array Objects (VAO)

I Le rôle d’un VAO est d’indiquer quelles seront les valeurs des attributs du vertex shader actif lors du tracé : il fait lelien entre les buffers (les VBO) et les attributs ("paramètres" in du vertex shader).

I VAO = indiquer pour chaque attribut du Vertex Shader quel VBO sera utilisé.

I Un même VAO peut être appliqué à différents shaders (et le même shader à différents VAO).

I Comme la très grande majorité des "Objects" OpenGL, il faut : générer un identifiant de VAO, puis faire un bind pourle rendre actif et travailler dessus :

void GLAppl icat ion : : in i tVAO ( ) {glGenVertexArrays (1 ,& _vao ) ;g lB indVer texAr ray ( _vao ) ;

g lB indBu f fe r (GL_ARRAY_BUFFER, _ p o s i t i o n B u f f e r ) ;g l V e r t e x A t t r i b P o i n t e r (0 ,3 ,GL_FLOAT,GL_FALSE, 0 , 0 ) ;

g lEnab leVe r texA t t r i bA r ray ( 0 ) ;

g lB indVer texAr ray ( 0 ) ; / / par pré caut ion ( e f f e t de bord )}

I glVertexAttribPointer : associe l’attribut numéro 0 du shader qui sera actif lors du tracé (sur notre exemple ils’agit la variable position : cf glBindAttribLocation de l’initialisation du shader) au buffer ARRAY_BUFFER.

I Les données d’un buffer n’ont aucune interprétation : il faut donc préciser combien de composantes il faut prendre etde quel type pour l’attribut 0 (ici 3 float (x, y, z) pour chaque sommet).

I ...,GL_FALSE, 0, 0) : paramètres vus plus tard en TP.

I glEnableVertexAttribArray(0) : indique que l’attribut numéro 0 du shader actif lors du tracé doit être alimentépar un ARRAY_BUFFER (par défaut, ils sont aliméntés par des valeurs constantes).

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 26 / 66

Etats pour tracer

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 27 / 66

Tracé OpenGL

void GLAppl icat ion : : i n i t i a l i z e ( ) {/ / appelée 1 seule f o i s à l ’ i n i t i a l i s a t i o n du contexte/ / => i n i t i a l i s a t i o n s OpenGLg lC learCo lo r ( 1 , 1 , 1 , 1 ) ;

in i tProgramShader ( ) ;in i tVBO ( ) ;in i tVAO ( ) ;

}

void GLAppl icat ion : : draw ( ) {/ / appelée après chaque update/ / => t r a c e r tou te l ’ image

g lC lea r (GL_COLOR_BUFFER_BIT ) ;

glUseProgram ( _program ) ;g lB indVer texAr ray ( _vao ) ;glDrawArrays (GL_TRIANGLES, 0 , 6 ) ;glUseProgram ( 0 ) ;g lB indVer texAr ray ( 0 ) ;

}

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 28 / 66

Résumé

I Les données sont gérées par l’application (sur cet exemple, le tableau des coordonnéesdes triangles).

I Généralement les données (i.e. les modèles) sont plus complexes qu’un simple tableau :prévoir une phase de copie/transformation dans un tableau pour pouvoir ensuite copierdans les buffers OpenGL.

I Démarche :• Initialiser :

• Program Shader (inclut un Vertex Shader et un Fragment Shader) :compiler/linker les shaders (souvent fait une fois pour toute à l’initialisation).

• VBO : copier les données de l’application (positions, couleurs, etc dessommets) dans des buffers OpenGL (peut être dynamique avec une mise à jourde ces buffers).

• VAO : indiquer quel VBO alimentera chaque attribut des shaders (généralementfait une fois pour toute à l’initialisation).

• Pour tracer :• Activer un Program Shader (inclut un Vertex et un Fragment Shaders)• Activer un VAO (associe pour chaque attribut du Vertex Shader un VBO)• Faire un (ou plusieurs) glDraw (parcourt les VBO dans l’ordre : 3 premiers

sommets = premier triangle ; 3 sommets suivans = second triangle ; etc).

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 29 / 66

Résumé

I "Lourd"?

• la démarche devient rapidement systématique (quasi du copier-coller pour chaqueVAO, VBO et aisé à abstraire ; 2/3 shaders pour une application simple).

• beaucoup de framework allègent la gestion des shaders (lecture du code sourcedepuis des fichiers, puis compilation/link en une méthode), des VBO, et des VAO(avec, souvent, le risque de réduire leur richesse/liberté).

• comprendre l’intérêt : lors d’un glDrawArrays(GL_TRIANGLES,0,1500000)⇒ lecpu ne fait rien (tout est assuré par la carte graphique).

• souplesse de programmation des vertex/fragment shaders.

https ://www.shadertoy.com/F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 30 / 66

Page 6: Orientation du cours - FIL Lille 1aubert/m3ds/m3ds_intro... · 2019. 1. 13. · les frameworks GUI "usuels" (Qt, GTK+, wxWidgets, ...) proposent de gérer une fenêtre/widget OpenGL.

3 Paramétrisation des shaders (uniform)

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 31 / 66

Objectif

I Changer la couleur dans le fragment shader? (pas très dynamique...)

# vers ion 130

out vec4 f ragCo lo r ; / / s o r t i e = données du p i x e l

void main ( ) {f ragCo lo r=vec4 ( 0 , 1 , 0 , 1 ) ; / / rouge , ver t , bleu , alpha

}

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 32 / 66

Uniform

Fragment shader :

# vers ion 130

uni form vec4 co lo r ;

out vec4 f ragCo lo r ;

void main ( ) {f ragCo lo r= co lo r ;

}

I ⇒ on affecte la couleur depuis l’application :

void GLAppl icat ion : : draw ( ) {g lC lea r (GL_COLOR_BUFFER_BIT ) ;

glUseProgram ( _program ) ;

GLint l o c a t i o n C o l o r =glGetUni formLocat ion ( _program , " co l o r " ) ;g lUn i fo rm4f ( l oca t i onCo lo r , 0 , 1 , 0 , 1 ) ; / / t ou te va leur c a l c u l ée ou non

g lB indVer texAr ray ( _vao ) ;glDrawArrays (GL_TRIANGLES, 0 , 6 ) ;glUseProgram ( 0 ) ;g lB indVer texAr ray ( 0 ) ;

}

I Un uniform reste constant pendant tout le glDrawArrays (mais peut, bien sûr, être modifiéentre 2 glDrawArrays par l’application...)

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 33 / 66

4 Communication vertex/fragmentshaders (varying)

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 34 / 66

Objectif

I Il y a un attribut supplémentaire à chaque sommet (une couleur en plus de la position).

I En chaque pixel la couleur est interpolée (i.e. "moyenne pondérée").

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 35 / 66

Vertex/Fragment

Vertex :# vers ion 130

i n vec3 p o s i t i o n ; / / a t t r i b u t ( x , y , z )i n vec4 co lo r ; / / a t t r i b u t ( r , v , b , a )

out vec4 fCo lo r ; / / va ry ing : out pour ver tex , i n pour fragment

void main ( ) {fCo lo r = co lo r ;g l _ P o s i t i o n =vec4 ( pos i t i on , 1 . 0 ) ;

}

Fragment :# vers ion 130

i n vec4 fCo lo r ; / / c a l c u l ée par i n t e r p o l a t i o n des va leurs a f f e c t ées/ / dans l e ver tex shader ( vary ing )

out vec4 f ragCo lo r ;

void main ( ) {f ragCo lo r= fCo lo r ;

}

I fColor est affecté dans le vertex shader (exécuté pour chaque sommet du triangle tracé).I fColor est "récupéré" dans le fragment shader (exécuté pour chaque pixel du triangle

tracé) : la valeur récupérée est calculée par interpolation par OpenGL. C’est la "moyennepondérée" (selon la position du pixel) des 3 fColor calculés aux sommets du triangle.

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 36 / 66

Page 7: Orientation du cours - FIL Lille 1aubert/m3ds/m3ds_intro... · 2019. 1. 13. · les frameworks GUI "usuels" (Qt, GTK+, wxWidgets, ...) proposent de gérer une fenêtre/widget OpenGL.

Interpolation

I Bien comprendre le processus :

• la couleur fColor est affectée uniquement aux sommets par le vertex shader (pourun triangle = 3 valeurs).

• lors de la rasterization (remplissage pixel par pixel), chaque fragment (triangle de 500pixels = 500 exécutions du fragment shader) récupère une valeur fColor calculée(par interpolation).

• ces variables calculées entre le vertex shader (avec out) et le fragment shader (avecin) sont souvent appelées varying (ancienne syntaxe).

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 37 / 66

Interpolation linéaire

M = (1−λ)V0 +λV1 (avec λ ∈ [0,1])

Interpoler linéairement la valeur f entre V0 et V1 signifie qu’on considère que f varielinéairement entre V0 et V1 (la variation est constante entre f (V0) et f (V1)).

⇒ f (M) = (1−λ)f (V0)+λf (V1)

I Remarque : calcul de λ connaissant V0, V1 et M ?

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 38 / 66

Interpolation bilinéaire (triangle)

I Interpolation linéaire sur [V2V0 ] : M1 = (1−λ1)V2 +λ1V0 ⇒ f (M1) = (1−λ1)f (V2)+λ1 f (V0)

I Interpolation linéaire sur [V2V1 ] : M2 = (1−λ2)V2 +λ2V1 ⇒ f (M2) = (1−λ2)f (V2)+λ2 f (V1)

I Interpolation linéaire sur [M1 ,M2 ] : M = (1−λ)M1 +λM2 ⇒ f (M) = (1−λ)f (M1)+λf (M2)

Remarques :I « en dessous »de V0, il faut poursuivre le calcul sur M1 avec les sommets V0 et V1.

I Toute valeur varying sera calculée ainsi avant l’exécution d’un fragment shader (dans le principe ; le calcul exact est à nuancer avec la correction de perspective quisera vue plus tard).

I Appliquée à la couleur, cette interpolation est appelée interpolation de Gouraud (ou « lissage »de Gouraud = Gouraud Shading).

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 39 / 66

Couleurs des sommets dans VBO

I Il faut spécifier la couleur en chaque sommet (en plus des coordonnées) :

GLAppl icat ion : : GLAppl icat ion ( ) {_pos i t ionData ={−0.8 ,0.0 ,−0.3 , / / ve r tex 0 / / f i r s t t r i a n g l e

0.3 ,−0.7 ,−0.3 , / / ve r tex 10.0 ,0.9 ,−0.3 , / / ve r tex 20.4 ,−0.5 ,0.4 , / / ve r tex 3 / / second t r i a n g l e0 .9 ,0 .4 ,0 .4 , / / ve r tex 40.8 ,−0.9 ,0.4 / / ve r tex 5

} ;_colorData = { 1 . 0 , 0 . 0 ,0 . 0 ,1 .0 , / / co l o r 0 / / f i r s t t r i a n g l e

0 . 0 ,1 .0 ,0 .0 ,1 .0 , / / co l o r 10 . 0 ,0 .0 ,1 .0 ,1 .0 , / / co l o r 20 . 5 ,0 .8 ,0 .2 ,1 .0 , / / co l o r 3 / / second t r i a n g l e0 . 8 ,0 .1 ,0 .0 ,1 .0 ,0 .1 ,0 .7 ,0 .8 ,1 .0

} ;}

void GLAppl icat ion : : in i tVBO ( ) {g lGenBuffers (1 ,& _ p o s i t i o n B u f f e r ) ;g lB indBu f fe r (GL_ARRAY_BUFFER, _ p o s i t i o n B u f f e r ) ;g lBu f fe rDa ta (GL_ARRAY_BUFFER, _pos i t ionData . s ize ()∗ s i z e o f ( f l o a t ) , _pos i t ionData . data ( ) ,GL_STATIC_DRAW ) ;

glGenBuffers (1 ,& _co lo rBu f f e r ) ;g lB indBu f fe r (GL_ARRAY_BUFFER, _c o lo rBu f f e r ) ;g lBu f fe rDa ta (GL_ARRAY_BUFFER, _colorData . s ize ()∗ s i z e o f ( f l o a t ) , _colorData . data ( ) ,GL_STATIC_DRAW ) ;

}

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 40 / 66

Modifications VAO

I Ne pas oublier de faire la correspondance numéro d’attribut/nom de l’attribut lors del’initialisation du program shader :

void GLAppl icat ion : : in i tProgramShader ( ) {/ / . . . read , compile , l i n k shader/ / . . .

g l B i n d A t t r i b L o c a t i o n ( _program ,0 , " p o s i t i o n " ) ;g l B i n d A t t r i b L o c a t i o n ( _program ,1 , " cou leur " ) ;

glLinkProgram ( _program ) ;}

I Faire la correspondance numéro d’attribut/VBO dans le VAO :

void GLAppl icat ion : : in i tVAO ( ) {glGenVertexArrays (1 ,& _vao ) ;g lB indVer texAr ray ( _vao ) ;

/ / p o s i t i o n = a t t r i b u t e 0g lB indBu f fe r (GL_ARRAY_BUFFER, _ p o s i t i o n B u f f e r ) ;g l V e r t e x A t t r i b P o i n t e r (0 ,3 ,GL_FLOAT,GL_FALSE, 0 , 0 ) ;

/ / co l o r = a t t r i b u t e 1g lB indBu f fe r (GL_ARRAY_BUFFER, _c o lo rBu f f e r ) ;g l V e r t e x A t t r i b P o i n t e r (1 ,4 ,GL_FLOAT,GL_FALSE, 0 , 0 ) ;

g lEnab leVe r texA t t r i bA r ray ( 0 ) ;g lEnab leVe r texA t t r i bA r ray ( 1 ) ;

g lB indVer texAr ray ( 0 ) ;}

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 41 / 66

5 Quelques constructions (Attributs desommets et Indexed Face Sets)

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 42 / 66

Page 8: Orientation du cours - FIL Lille 1aubert/m3ds/m3ds_intro... · 2019. 1. 13. · les frameworks GUI "usuels" (Qt, GTK+, wxWidgets, ...) proposent de gérer une fenêtre/widget OpenGL.

Exercice

I On souhaite :

Plusieurs solutions (2 glDraw avec uniform, 1 glDraw avec attributs).

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 43 / 66

Exercice

On dispose de :

_pos i t ionData = {V0 , V1 , V2 , V3 , V4 , V5 , V6 , V7 } ; ( pseudo−code : c ’ es t un tab leau de f l o a t { x0 , y0 , z0 , x1 , y1 , z1 , . . . e tc } ) .

I On souhaite :

I Remarque : ordre des sommets et un sommet en commun.

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 44 / 66

Indexed Face Set

I On peut donner d’une part les sommets (i.e. leurs coordonnées), et d’autre part commentils sont reliés les uns aux autres pour former les triangles (en donnant la succession desindices des sommets).

GLAppl icat ion : : GLAppl icat ion ( ) {. . .

_pos i t ionData = {V0 , V1 , V2 , V3 , V4 , V5 , V6 , V7 } ; ( pseudo−code : c ’ es t un tab leau de f l o a t { x0 , y0 , z0 , x1 , y1 , z1 , . . . e tc } ) ._indexData ={2 ,0 ,5 ,1 ,4 ,3 ,7 ,3 ,6 } ; / / i nd i ces des sommets ( selon ordre du VBO)

. . .}

vo id GLAppl icat ion : : in i tVBO ( ) {/ / . . . c f in i tVBO précédent

glGenBuffers (1 ,& _ indexBuf fe r ) ;/ / A t t e n t i o n à l a c i b l e du Bind et de l a copie ! ! ! :/ / ne pas confondre ARRAY_BUFFER et ELEMENT_ARRAY_BUFFERg lB indBu f fe r (GL_ELEMENT_ARRAY_BUFFER, _ indexBuf fe r ) ;g lBu f fe rDa ta (GL_ELEMENT_ARRAY_BUFFER, _indexData . s ize ()∗ s i z e o f ( unsigned i n t ) , _indexData . data ( ) ,GL_STATIC_DRAW ) ;

}

vo id GLAppl icat ion : : in i tVAO ( ) {glGenVertexArrays (1 ,& _vao ) ;g lB indVer texAr ray ( _vao ) ;/ / . . . c f VAO précédent/ / A t t e n t i o n à l a c i b l eg lB indBu f fe r (GL_ELEMENT_ARRAY_BUFFER, _ indexBuf fe r ) ;g lB indVer texAr ray ( 0 ) ;

}

vo id GLAppl icat ion : : draw ( ) {/ / . . . c f draw précédentg lB indVer texAr ray ( _vao ) ;/ / 9 i nd i ces à prendre ( i . e . 9 r é f érences à des sommets = 3 t r i a n g l e s )glDrawElements (GL_TRIANGLES,9 ,GL_UNSIGNED_INT , 0 ) ;/ / . . .

} F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 45 / 66

Exercice

I On souhaite :

⇒ glDrawArrays(GL_TRIANGLE_STRIP,...)I On souhaite :

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 46 / 66

Exercice anneau

⇒ on peut ("bien sûr") faire glDrawElements avec GL_TRIANGLE_STRIP._pos i t ionData ={V0 , V1 , V2 , V3 , V4 , V5 , V6 , V7 } ;_elementData ={0 ,1 ,2 ,3 ,4 ,5 ,6 ,7 ,0 ,1 } ;. . .

glDrawElements (GL_TRIANGLE_STRIP,10 ,GL_UNSIGNED_INT , 0 ) ;. . .

I Est-ce qu’il faut préférer la redondance des sommets à la fin (glDrawArrays(GL_TRIANGLE_STRIP,...) oufaire un index (glDrawElements(GL_TRIANGLE_STRIP,...)) ??

I Le GL_TRIANGLE_STRIP peut demander un gros effort d’organisation des triangles (ordre dessommets, découpage, etc) : pas si souvent utilisé que ça en pratique.

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 47 / 66

Exercice

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 48 / 66

Page 9: Orientation du cours - FIL Lille 1aubert/m3ds/m3ds_intro... · 2019. 1. 13. · les frameworks GUI "usuels" (Qt, GTK+, wxWidgets, ...) proposent de gérer une fenêtre/widget OpenGL.

Exercice

(tracé avec glPolygonMode(GL_FRONT_AND_BACK,GL_FILL))

(tracé avec glPolygonMode(GL_FRONT_AND_BACK,GL_LINE))

_pos i t ionData . c l ea r ( ) ;_pos i t ionData . push_back ( 0 . 0 ) ;_pos i t ionData . push_back ( 0 . 0 ) ;_pos i t ionData . push_back ( 0 . 0 ) ;i n t nbSl ice =100;f l o a t stepTheta =2.0∗3.14159/ nbSl ice ;f l o a t t he ta =0 .0 ;double x , y , z =0;for ( i n t i =0; i <nbSl ice ; i ++) {

x=0.5∗cos ( the ta ) ;y=0.5∗ s in ( the ta ) ;

_pos i t ionData . push_back ( x ) ;_pos i t ionData . push_back ( y ) ;_pos i t ionData . push_back ( z ) ;the ta +=stepTheta ;

}_pos i t ionData . push_back ( 0 . 5 ) ;_pos i t ionData . push_back ( 0 . 0 ) ;_pos i t ionData . push_back ( 0 . 0 ) ;

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 49 / 66

Sommet = tous ses attributs

_pos i t ionData ={ V0 , V1 , V2 , V3 } ;_colorData= { rouge , ver t , rouge , bleu } ; / / pseudo−code_indexData = {0 ,1 ,2 ,0 ,2 ,3 } ;. . .glDrawElements (GL_TRIANGLES,6 ,GL_UNSIGNED_INT , 0 ) ;

I Remarque : non tracé en GL_TRIANGLE_STRIP pour comparer àl’illustration suivante.

_pos i t ionData ={ V0 , V1 , V2 , V3 , V4 , V5 } ;_colorData= { rouge , ver t , rouge , bleu , ver t , b leu } ; / / pseudo−code_indexData = {0 ,1 ,2 ,4 ,5 ,3 } ;. . .glDrawElements (GL_TRIANGLES,6 ,GL_UNSIGNED_INT , 0 ) ;

I V4 = V0 et V5 = V2 : V0 et V2 doivent être dupliqués car ils n’ontpas la même couleur (il n’y a qu’un seulELEMENT_ARRAY_BUFFER : chaque indice concerne tous lesattributs).

I ⇒ 1 sommet = tous ses attributs

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 50 / 66

6 Texture

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 51 / 66

Résultat

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 52 / 66

Texture

I Texture = "données" (ici une image : chaque élément est un triplet (rouge,vert,bleu))I Chaque élément = texel (analogie avec pixel).I Les texels sont localisés par des coordonnées (s, t) normalisées (∈ [0,1]).

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 53 / 66

Coordonnées de textures

_pos i t ionData ={−0.8 ,0.0 ,−0.3 , / / ve r tex 0 / / f i r s t t r i a n g l e0.3 ,−0.7 ,−0.3 , / / ve r tex 10.0 ,0.9 ,−0.3 , / / ve r tex 20.4 ,−0.5 ,0.4 , / / ve r tex 3 / / second t r i a n g l e0 .9 ,0 .4 ,0 .4 , / / ve r tex 40.8 ,−0.9 ,0.4 / / ve r tex 5

} ;_texCoordData ={

0 .2 ,0 .3 , / / texCoord f o r V00 .6 ,0 .2 , / / texCoord f o r V10 .1 ,0 .9 , / / texCoord f o r V20 .7 ,0 .7 , / / texCoord f o r V30 .9 ,0 .1 , / / texCoord f o r V40 .9 ,0 .7 / / texCoord f o r V5

} ;

I A chaque sommet on indique lescoordonnées de texture (attribut).

I Pour ce résultat :• les coordonnées de texture seront interpolées

lors de la rasterization (varying).• on affecte la couleur du pixel (fragment

shader) avec la couleur du texel qui se trouveà ces coordonnées de texture.

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 54 / 66

Page 10: Orientation du cours - FIL Lille 1aubert/m3ds/m3ds_intro... · 2019. 1. 13. · les frameworks GUI "usuels" (Qt, GTK+, wxWidgets, ...) proposent de gérer une fenêtre/widget OpenGL.

Texture Object

void GLAppl icat ion : : i n i t T e x t u r e ( ) {/ / load image ( image loader l i b r a r y requ i red . . . )

QImage img ;img . load ( " . . / media / lagoon . jpg " ) ;img=img . convertToFormat ( QImage : : Format_ARGB32 ) . mi r ro red ( ) ; / / Qt Image (0 ,0 ) i s l e f t−top => mi r ro red

/ / t e x t u r e Object ( t a r g e t GL_TEXTURE_2D)glGenTextures (1 ,& _ t e x t u r e I d ) ;g lB indTexture (GL_TEXTURE_2D, _ t e x t u r e I d ) ;glTexImage2D (GL_TEXTURE_2D,0 ,GL_RGBA, img . width ( ) , img . he igh t ( ) , 0 ,GL_BGRA,GL_UNSIGNED_BYTE, img . b i t s ( ) ) ;

g lTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ) ;glTexParameterf (GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER, GL_LINEAR ) ;

glTexParameterf (GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT ) ;glTexParameterf (GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT ) ;

}

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 55 / 66

VBO/VAO

I Idem que les positions, couleurs, ...

void GLAppl icat ion : : i n i t B u f f e r ( ) {. . .g lGenBuffers (1 ,& _texCoordBuf fer ) ;g lB indBu f fe r (GL_ARRAY_BUFFER, _texCoordBuf fer ) ;g lBu f fe rDa ta (GL_ARRAY_BUFFER, _texCoordData . s ize ()∗ s i z e o f ( f l o a t ) , _texCoordData . data ( ) ,GL_STATIC_DRAW ) ;. . .

}

void GLAppl icat ion : : in i tVAO ( ) {glGenVertexArrays (1 ,& _vao ) ;g lB indVer texAr ray ( _vao ) ;/ / p o s i t i o n = a t t r i b u t e 0g lB indBu f fe r (GL_ARRAY_BUFFER, _ p o s i t i o n B u f f e r ) ;g l V e r t e x A t t r i b P o i n t e r (0 ,3 ,GL_FLOAT,GL_FALSE, 0 , 0 ) ;/ / texCoord = a t t r i b u t e 1g lB indBu f fe r (GL_ARRAY_BUFFER, _texCoordBuf fer ) ;g l V e r t e x A t t r i b P o i n t e r (1 ,2 ,GL_FLOAT,GL_FALSE, 0 , 0 ) ;

g lEnab leVe r texA t t r i bA r ray ( 0 ) ;g lEnab leVe r texA t t r i bA r ray ( 1 ) ;

g lB indVer texAr ray ( 0 ) ;}

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 56 / 66

Shaders

I Coordonnées de textures aux sommets = attributs (comme les autres données auxsommets)

I La texture elle-même (l’ensemble des texels) = uniform de type sampler2D

I Vertex shader :

# vers ion 130

i n vec3 p o s i t i o n ; / / a t t r i b u t ( x , y , z )i n vec2 texCoord ; / / a t t r i b u t ( s , t )

out vec2 fTexCoord ; / / out pour ver tex , i n pour fragment

void main ( ) {fTexCoord = texCoord ;g l _ P o s i t i o n =vec4 ( pos i t i on , 1 . 0 ) ;

}

I Fragment :

# vers ion 130

uni form sampler2D texUn i t ;

i n vec2 fTexCoord ;

out vec4 f ragCo lo r ;

void main ( ) {f ragCo lo r= t e x t u r e ( texUn i t , fTexCoord ) ;

}

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 57 / 66

Unité de texture

# vers ion 130

uni form sampler2D texUn i t ;

i n vec2 fTexCoord ;

out vec4 f ragCo lo r ;

void main ( ) {f ragCo lo r= t e x t u r e ( texUn i t , fTexCoord ) ;

}

I Attention : texUnit ne sera pas affecté avec un identifiant de texture (i.e. _textureId dans l’exemple) mais avecune unité de texture (i.e. nombre entre 0 et 7).

I Il faut donc préciser quelle identifiant de texture est affectée à l’unité de texture souhaitée.

void GLAppl icat ion : : draw ( ) {/ / appelée après chaque update/ / => t r a c e r tou te l ’ imageg lC lea r (GL_COLOR_BUFFER_BIT ) ;

glUseProgram ( _program ) ;

g lAc t i veTex tu re (GL_TEXTURE0 ) ;g lB indTexture (GL_TEXTURE_2D, _ t e x t u r e I d ) ;

i n t l oca t i onTexUn i t =g lGetUni formLocat ion ( _program . i d ( ) , " t exUn i t " ) ;g lUn i fo rm1 i ( loca t ionTexUn i t , 0 ) ;

g lB indVer texAr ray ( _vao ) ;glDrawArrays (GL_TRIANGLES, 0 , 6 ) ;glUseProgram ( 0 ) ;g lB indVer texAr ray ( 0 ) ;

}

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 58 / 66

7 Normalized Device Coordinates etWindow Coordinates

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 59 / 66

Volume de visualisation

I Les coordonnées (x ,y ,z) des sommets visibles sont dans [−1,1] : définit le volume devisualisation en Normalized Device Coordinates (NDC).

I Des sommets extérieurs à ce volume provoquent une opération de clipping par OpenGL(découpage des triangles).

_pos i t ionData ={−1.3 ,0.0 ,−0.3 , / / ve r tex 0 / / f i r s t t r i a n g l e0.3 ,−0.7 ,−0.3 , / / ve r tex 10.0 ,0.9 ,−0.3 , / / ve r tex 20.4 ,−0.5 ,0.4 , / / ve r tex 3 / / second t r i a n g l e1 .5 ,0 .4 ,0 .4 , / / ve r tex 40.8 ,−1.3 ,0.4 / / ve r tex 5

} ;

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 60 / 66

Page 11: Orientation du cours - FIL Lille 1aubert/m3ds/m3ds_intro... · 2019. 1. 13. · les frameworks GUI "usuels" (Qt, GTK+, wxWidgets, ...) proposent de gérer une fenêtre/widget OpenGL.

Clipping

_pos i t ionData ={−1.3 ,0.0 ,−0.3 , / / ve r tex 0 / / f i r s t t r i a n g l e0.3 ,−0.7 ,−0.3 , / / ve r tex 10.0 ,0.9 ,−1.3 , / / ve r tex 20.4 ,−0.5 ,0.4 , / / ve r tex 3 / / second t r i a n g l e1 .5 ,0 .4 ,0 .4 , / / ve r tex 40.8 ,−1.3 ,0.4 / / ve r tex 5

} ;

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 61 / 66

Window Coordinates et Normalized Device Coordinates

I On travaille avec des coordonnées en Normalized Device Coordinates (i.e. NDC).I Mais lors de la rasterization (tracé pixel par pixel) dans la fenêtre graphique, OpenGL doit

fournir des pixels dont les coordonnées doivent être connues (par le serveur graphique)en coordonnées de la fenêtre graphique (par exemple tracé dans une fenêtre graphiquede 256x512 pixels) :• C’est le rôle de l’instruction glViewport(xv,yv,width,height) (obligatoire ; cf tout

premier code du cours).• Par exemple, pour glViewport(10,20,256,512), reportera

xNDC ∈ [−1,1],yNDC ∈ [−1,1] dans xwindow ∈ [10,266],ywindow ∈ [20,532].• Les coordonnées pixels (i.e. transformation par le viewport) sont appelées Window

Coordinates.• Remarque : le zNDC ∈ [−1,1] subit également un report pour obtenir zwindow dans

[0,1] (indépendant du viewport). zwindow est généralement appelé depth(profondeur) et nous verrons son utilisation dans le chapitre suivant.

xwindow = (1+ xNDC)width

2 + xvywindow = (1+ yNDC)

height2 + yv

zwindow = (1+ zNDC)/2.0• Remarque : les window coordinates sont accessibles dans le fragment shader par la

variable prédéfinie gl_FragCoord (gl_FragCoord.z contenant la profondeur).

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 62 / 66

8 Quelques remarques pour finir...

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 63 / 66

Copie buffer

I Si la valeur des attributs est dynamique (modifications de la position des sommets parexemple), on utilisera glSubBufferData pour mettre à jour les buffers (glBufferDatadétruit/réalloue à chaque appel).

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 64 / 66

Buffer entrelacé

I Buffer entrelacé : un même VBO peut recevoir les données d’attributs distincts (positions etcouleurs par exemple).

I Le VAO permet de préciser comment affecter les différents attributs (gràce aux paramètresde glVertexAttribPointer).

/ / c l i e n t data = { x0 , y0 , z0 , r0 , g0 , b0 , a0 , x1 , y1 , . . . } = { coordonnées 0 , cou leur 0 , . . . }_a l lDa ta ={−1 ,1 ,0 , 1 ,0 ,0 ,1 , −1,−1,0, 0 ,1 ,0 ,1 , 1 ,1 ,0 , 0 ,0 ,1 ,1 , 1 ,−1 ,0 , 1 ,1 ,0 ,1 } ;/ / i n i t b u f f e rglGenBuffers (1 ,& _ a l l B u f f e r ) ;g lB indBu f fe r (GL_ARRAY_BUFFER, _ a l l B u f f e r ) ;g lBu f fe rDa ta (GL_ARRAY_BUFFER, _a l lDa ta . s i ze ()∗ s i z e o f ( f l o a t ) , _a l lDa ta . data ( ) ,GL_STATIC_DRAW ) ;/ / vaog lB indBu f fe r (GL_ARRAY_BUFFER, _ a l l B u f f e r ) ;/ / pour l a p o s i t i o n ( a t t r i b u t 0) : 3 f l o a t s par sommet , é c a r t de 7 f l o a t en t re 2 p o s i t i o n s :g l V e r t e x A t t r i b P o i n t e r (0 ,3 ,GL_FLOAT,GL_FALSE, s i z e o f ( f l o a t )∗7 ,0) ;/ / pour l a cou leur ( a t t r i b u t 1) : 4 f l o a t s par sommet , é c a r t de 7 f l o a t en t re 2 couleurs e t commence après 3 f l o a tg l V e r t e x A t t r i b P o i n t e r (1 ,4 ,GL_FLOAT,GL_FALSE, s i z e o f ( f l o a t )∗7 ,( void ∗)(3∗ s i z e o f ( f l o a t ) ) ) ;

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 65 / 66

Primitives de tracé

I GL_TRIANGLES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN, GL_LINES, GL_LINE_STRIP,GL_LINE_LOOP, GL_POINTS (+ versions _ADJACENCY, GL_PATCHES).

F. Aubert M3DS/ 1 - Introduction - Programmation 3D Master Informatique2018-2019 66 / 66