cours de mii 2 - biri/enseignement/mii2/tdpdf/... · optix, nvidia 2008 “renderants: interactive...
TRANSCRIPT
1
Cours de MII 2
GPGPU
2
GPGPU
Objectif du cours :Comprendre les architectures GPU
Comprendre la programmation parallèle sur GPU
Maîtriser la programmation Cuda
Contenu :1 ou 2 cours magistraux
2 ou 3 séances de TP
Notations :1 projet & TP notés
3
GPGPU
Plan
1. Introduction
2. Architecture
3. GPGPU on the GPU
4. GPGPU via Cuda
5. Exemple et optimisation
4
GPGPU
1. Introduction
5
History of 3D
6
History of 3D
7
The way it uses to be...
Fixed Function Pipelines (DX7)Writing new rendering algorithms means
♦ Tricks with multitexture, stencil buffer, depth buffer, blending …
Examples♦ Stencil shadow volumes♦ Hidden line removal♦ ...
8
The way it uses to be...
The fixed function pipeline
9
The way it uses to be...
Programmable Shaders (DX8-10)Writing new rendering algorithms means
♦ Tricks with stencil buffer, depth buffer, blending♦ Plus: Writing shaders
Examples♦ User-defined materials♦ User-defined lights♦ User-defined data structures (built in texture memory)
10
The way it uses to be...
Programmable pipeline
11
The way it begins to be...
Software Graphics: Part I (DX11)Writing new rendering algorithms means
♦ Tricks with stencil buffer, depth buffer, blending…♦ Plus: Writing shaders♦ Plus: Writing data-and task-parallel algorithms
Analyze results of rendering pipeline Synthesize data structures
Examples♦ Dynamic summed area table♦ Dynamic quadtree adaptive shadow map♦ Dynamic histogram-analysis shadow map♦ Dynamic ambient occlusion
12
Examples (DX 11)
“Real-Time Approximate Sorting for Self Shadowing and Transparency in Hair Rendering,”
Sintornet al., I3D 2008
“Dynamic Ambient Occlusion and Indirect Lighting,” Bunnell, GPU Gems II, 2005
“Fast Summed- Area Table Generation and its Applications,” Hensley et al., Eurographics2005
13
The way it begins to be...
Software Graphics: Part II (DX11+)Writing new rendering algorithms means
♦ Tricks with stencil buffer, depth buffer, blending♦ Plus: Writing shaders♦ Plus: Writing data-and task-parallel algorithms♦ Plus: Creating new and extended rendering pipelines
Examples♦ Micropolygon rendering♦ Ray tracing pipelines
14
Examples
OptiX, NVIDIA 2008 “RenderAnts: Interactive Reyes Rendering on GPUs,” Zhou et al., ACM SIGGRAPH Asia
“Hardware-Accelerated Global Illuminationby Image Space Photon Mapping ,” McGuire and Luebke, HPG 09
“FreePipe: a Programmable Parallel Rendering Architecture for Efficient Multi-Fragment Effects ,” Liu et al.,
ACM SIGGRAPH 2010
CUDAinside
CUDAinside
15
The way it will be...
“Render to Data Structures”DX11 PixelShader5
♦ Atomics to global memory♦ Gather/scatter to memory (“unordered access views”
Order independent transparency♦ Capture all rendered fragments
Render directly to grid-of-lists data structure instead of FB No framebuffer bound while rendering Increment global counter to get unique address for fragment Result is grid of linked lists
♦ Sort and blend lists for final image (pixel shader or compute shader)
16
The way it will be...
17
GPU Programming ?
GPU stands for Graphics Processing UnitSimply – It is the processor that resides on your
graphics card.
GPUs allow us to achieve the unprecedented graphics capabilities now available in games
18
CPU vs GPU
Why use GPU ?
19
CPU vs GPU
A quiet revolution and potential build-upCalculation: 367 GFLOPS vs. 32 GFLOPS
Memory Bandwidth: 86.4 GB/s vs. 8.4 GB/s
Until last couple years, programmed through graphics API
GPU in every PC and workstation – massive volume and potential impact
20
GPU Programming ?
How has this comes about ? Game design has become ever more sophisticated.
Fast GPUs are used to implement complex shader and rendering operations for real-time effects.
In turn, the demand for speed has led to ever-increasing innovation in card design.
The NV40 architecture has 225 million transistors, compared to about 175 million for the Pentium 4 EE 3.2 Ghz chip.
The gaming industry has overtaken the defense, finance, oil and healthcare industries as the main driving factor for high performance processors.
21
GPU Programming ?
GPU speed increasing at cubed-Moore’s Law.This is a consequence of the data-parallel
streaming aspects of the GPU.
GPUs are cheap ! Put a couple together, and you can get a super-computer
Warning ! Various granularities of parallelism exist, but…programming model must not hinder parallel
implementation
data delivery needs careful management
Voronoi DiagramsData Analysis Motion Planning
Geometric Optimization
Physical Simulation
Matrix Multiplication
Conjugate Gradient Sorting and Searching
Force-field simulation
Particle Systems
Molecular Dynamics Graph Drawing
Signal Processing
Database queries
Range queries
… and graphics too !!
Image Processing
Radar, Sonar, Oil ExplorationFinance
Planning
Optimization
Wealth of applications
Wealth of applications
24
GPU Programming ?
A Unifying theme: StreamingAll the graphics language models share basic
properties:1. They view the frame buffer as an array of “pixel
computers”, with the same program running at each pixel (SIMD)
2. Fragments are streamed to each pixel computer
3. The pixel programs have limited state. All the GPGPU language works the same
1. They view problem as an array of threads
2. Data elements are streamed to each thread
3. The threads have limited memory / computing power
25
Stream programming?
A stream is a sequence of datacould be numbers, colors, RGBA vectors,…
A kernel is a (fragment) program runs on each element of a stream
generating an output stream (pixel buffer)
26
Stream programming?
Two main ways of doing stream programmingThe pure GPU way
♦ Using the graphic programmable pipeline♦ Language : Cg, HLSL, GLSL
The GPGPU way♦ Using high level abstraction library♦ Language : BrookGPU, CUDA, OpenCL
27
Stream program on GPU
Kernel vertex/fragment program
Input stream stream of fragments or vertices or texture data
Output stream frame buffer or pixel buffer or texture
Multiple kernels multi-pass rendering sequence on the GPU
28
Stream program on GPGPU
Kernel User defined function
Input stream Stream of any data (float mainly)
Output stream Stream of any data (float mainly)
Multiple kernels Multi-pass execution of kernel on the GPU with
synchronization
29
Stream programming
To program the GPU, one must think of it as a (parallel) stream
processor.
30
GPGPU
2. Architecture
31
GPU Architecture
Nomenclature :Kernel : treatment unit
Thread : a single processing unit
Host : application hardware (CPU)
Device : coprocessor hardware (GPU)
32
Architecture GeForce 7800 GTX
Triangle Setup/RasterTriangle Setup/Raster
Shader Instruction DispatchShader Instruction Dispatch
Fragment CrossbarFragment Crossbar
MemoryPartitionMemoryPartition
MemoryPartitionMemoryPartition
MemoryPartitionMemoryPartition
MemoryPartitionMemoryPartition
Z-CullZ-Cull
8 Vertex Engines
24 Pixel Shaders
16 Raster Operation Pipelines
33
Architecture G80 graphic mode
L2
FB
SP SP
L1
TF
Th
rea
d P
roc
es
so
r
Vtx Thread Issue
Setup / Rstr / ZCull
Geom Thread Issue Pixel Thread Issue
Input Assembler
Host
SP SP
L1
TF
SP SP
L1
TF
SP SP
L1
TF
SP SP
L1
TF
SP SP
L1
TF
SP SP
L1
TF
SP SP
L1
TF
L2
FB
L2
FB
L2
FB
L2
FB
L2
FB
The future of GPU is programmable processing ?Build the architecture around the processor
34
Architecture G80 CUDA mode
Load/store
Global Memory
Thread Execution Manager
Input Assembler
Host
Texture Texture Texture Texture Texture Texture Texture TextureTexture
Parallel DataCache
Parallel DataCache
Parallel DataCache
Parallel DataCache
Parallel DataCache
Parallel DataCache
Parallel DataCache
Parallel DataCache
Load/store Load/store Load/store Load/store Load/store
Processors execute computing threadsNew operating mode/HW interface for computing
35
GPU Architecture
What is behind such an evolution ? GPU specialized for compute-intensive, highly data parallel
computation (exactly what graphics rendering is about)
So, more transistors can be devoted to data processing rather than data caching and flow control
36
GPU Architecture
Pipeline/Architecture of GPU (graphic mode)
37
GPGPU Architecture
Each « processor unit » can host a thread
Kernel are launch on arrays of threadEach thread runs the same code (SPMD)
Each thread has an ID that it uses to compute memory addresses and make control decisions
…float x = input[threadID];float y = func(x);output[threadID] = y;…
threadID 76543210
38
GPGPU Architecture
Kernel : grid of blocks
All thread share a single memory space
Blocks : batch of threads
Cooperates through♦ Execution synchronization♦ Shared memory
Thread in different blocks cannot cooperate
39
GPGPU Architecture
How can we distinct a thread from one other ?Each thread has an Id
♦ Can decide what data to work with
Each block has also an Id
Device
Grid 1
Block(0, 0)
Block(1, 0)
Block(2, 0)
Block(0, 1)
Block(1, 1)
Block(2, 1)
Block (1, 1)
Thread(0, 1)
Thread(1, 1)
Thread(2, 1)
Thread(3, 1)
Thread(4, 1)
Thread(0, 2)
Thread(1, 2)
Thread(2, 2)
Thread(3, 2)
Thread(4, 2)
Thread(0, 0)
Thread(1, 0)
Thread(2, 0)
Thread(3, 0)
Thread(4, 0)
40
GPGPU Architecture
Blocks can be 1D or 2D
Means Id are 1D or 2D
Threads can be 1, 2 or 3D
Means Id are the same
Simplifies memory addressing when processing multidimensional data
Image processing
Solving PDE on volumes...
Device
Grid 1
Block(0, 0)
Block(1, 0)
Block(2, 0)
Block(0, 1)
Block(1, 1)
Block(2, 1)
Block (1, 1)
Thread(0, 1)
Thread(1, 1)
Thread(2, 1)
Thread(3, 1)
Thread(4, 1)
Thread(0, 2)
Thread(1, 2)
Thread(2, 2)
Thread(3, 2)
Thread(4, 2)
Thread(0, 0)
Thread(1, 0)
Thread(2, 0)
Thread(3, 0)
Thread(4, 0)
41
Memory
Comparison CPU memory vs. GPU one
CPU Memory : At any program point
Allocate/free local or global memory
Random memory access
Registers♦ Read/write
Local memory♦ Read/write to stack
Global memory♦ Read/write to heap
Disk♦ Read/write to disk
42
GPU Memory
GPU Memory : restricted accesAllocate/free memory only before computation
Limited memory access during computation (kernel)♦ Registers
Read/write♦ Local memory
Read/write♦ Shared Memory
Only available in GPGPU not Graphics pipeline
43
GPU Memory
♦ Global memory Read-only during computation Write-only at end of computation Read/write in GPGPU world only
♦ Virtual Memory Does not exist !
♦ Disk access Does not exist !
44
GPU Memory
Where is GPU data storedVertex buffer
Frame buffer
Texture
Vertex BufferVertex
ProcessorRasterizer
FragmentProcessor
Texture
Frame Buffer(s)
45
GPU Memory
Vertex buffer Store geometric and radiometric data
FramebufferStore image based data (color, depth, stencil...)
TextureStore any kind of information (color, normal,
radiometric data ...)
46
GPGPU Memory
Acces also restricted
Each thread can:
R/W per-thread registers
R/W per-thread local memory
R/W per-block shared memory
R/W per-grid global memory
Read only per-grid constant memory
Read only per-grid texture memory
(Device) Grid
ConstantMemory
TextureMemory
GlobalMemory
Block (0, 0)
Shared Memory
LocalMemory
Thread (0, 0)
Registers
LocalMemory
Thread (1, 0)
Registers
Block (1, 0)
Shared Memory
LocalMemory
Thread (0, 0)
Registers
LocalMemory
Thread (1, 0)
Registers
Host
47
GPGPU Memory
The host can R/W global, constant, and texture memories
(Device) Grid
ConstantMemory
TextureMemory
GlobalMemory
Block (0, 0)
Shared Memory
LocalMemory
Thread (0, 0)
Registers
LocalMemory
Thread (1, 0)
Registers
Block (1, 0)
Shared Memory
LocalMemory
Thread (0, 0)
Registers
LocalMemory
Thread (1, 0)
Registers
Host
48
GPGPU Memory
Global memory : Long latency accesses !
Main means of communicating R/W Data between host and device
Contents visible to all threads
Constant and texture memoriesConstant initialized by host
Contents visible to all threads
49
GPGPU Memory
Per thread local memoryRegister
Per block memoryShared memory
Global memory
50
GPGPU
3. GPGPU on the GPU
51
GPGPU
3. GPGPU on the GPU3.1 les shaders
52
Cartes graphiques programmable
Deux emplacements majeurs programmables
53
Les shaders
Deux types de programmes :Les vertex program
Les fragment program
Intérêt :Adaptabilité du rendu
De nouveaux rendus (rapides !) :♦ Matériaux réalistes, Milieux participants,
Éclairage par fragment, Ombre, Éclairage réaliste…
Autres calculs que le rendu♦ Calcul matriciel, Lancer de rayon, Silhouette,
Traitement d’images, Animation …
54
Les shaders
Intérêts ?
55
Les shaders
56
Les vertex program :InformationsInformations
SommetSommet
VERTEXVERTEXPROGRAMPROGRAMTexturesTextures
VariablesVariablesgénériquesgénériques
sommetsommet
dont position, taille des points, clipdont position, taille des points, clip
Information sommet à interpolerInformation sommet à interpoler
Les shaders
57
Les fragment program :InformationsInformations
fragmentfragment
FRAGMENTFRAGMENTPROGRAMPROGRAM
Couleur du fragmentCouleur du fragmentProfondeur du fragmentProfondeur du fragment
TexturesTexturesVariablesVariables
génériquesgénériquesfragmentfragment
dont position (image) etdont position (image) etfront_facingfront_facing
Les shaders
58
Les shaders
Langage particulier pour piloter les programmesAssembleur
♦ Dépendent de la carte (ATI / Nvidia)♦ Pénible à écrire à la main♦ Code optimisé
Langages haut niveau au dessus de ces assembleursAppelés les shading languages : langages de
shaders
59
Les shaders
Historique des langages de shaderShading language : indépendant des cartes
graphiquesSorte d'unité programmable atomiqueRenderman Shading Language (Renderman 88)
♦ Adapté au lancer de rayon & rendu photoréaliste♦ Adresse 5 shaders différents : light, displacement,
surface, volume et imagerISL : Interactive Shading Language (SGI 00)
♦ Encore plus haut niveau. Génère des passes de rendu en OpenGL
♦ S’adresse directement à des instructions OpenGL
60
Les shaders
Historique des langages de shaderHLSL : High-Level Shader Language (Microsoft 02)
♦ Très proche de OpenGLSL : syntaxe, vertex & fragment♦ Adresse DirectX♦ Le shader n’est pas compilé par le driver
Cg : C graphic (Nvidia 02)♦ Très très similaire à HLSL (développé conjointement
avec Microsoft)♦ Ajout d’une couche librairie (Cg runtime library)♦ Adresse OpenGL et Direct X
OpenGLSL (OpenGL 03)♦ Décrit par la suite
61
GPGPU
3. GPGPU on the GPU3.2 OpenGLSL
62
GLSL : introduction
OpenGLSL : un langage de shader librePropriétés
♦ Lien et intégration simple avec Open GL♦ Flexible aux futures évolutions des cartes graphiques♦ Indépendant du hardware♦ Conserve les performances des cartes graphiques♦ Langage simple à utiliser♦ Convient à la norme OpenGL ARB (Arch. Review Board)♦ Permet les futures parallélisations dans les cartes
graphiques♦ Simple à optimiser (donc langage simple)
63
GLSL : introduction
Caractéristiques :Syntaxe identique à celle du C / C++Nouveaux types de données :
♦ Vecteurs♦ Matrices♦ Fragment de texture
Existence de variables et fonctions prédéfiniesOpérateurs surchargésPas de pointeur ni de référencePas de promotion (cast) implicitePassage d’argument par valeur
64
GLSL : introduction
Architecture :ApplicationApplication
Code source shaderCode source shader
OpenGL DriverOpenGL Driver
ObjetObjetshadershader
CompilatCompilateureur
ObjetObjetprogrprogrammeamme
LinkLinkerer
Code compiléCode compilé
Code exécutableCode exécutable
Carte graphiqueCarte graphique
OpenGL APIOpenGL API
65
GLSL : introduction
Avantages :Colle à OpenGLCompilation à l’exécutionIndépendant du hardwareCompilation par le driver => Meilleures
performancesStandard open source Fonctionne pour tout processus graphiques
♦ Donc peut être dans le futur les dernières parties non programmable
Pas besoin de librairie supplémentaire
66
GLSL : Types
Types disponibles :Scalaires : int / float / bool
♦ int : de –65535 à 65535♦ bool : true ou false
Vecteurs♦ vec2, vec3, vec4 : vecteur en float à 2, 3 ou 4
composantes♦ ivec2, ivec3, ivec4 : idem mais avec des entiers♦ bvec2, bvec3, bvec4 : idem mais avec des booléens♦ Accès aux composantes 1, 2, 3 ou 4 du vecteur vec par
vec.x / vec.y / vec.z / vec.w vec.r / vec.g / vec.b / vec.a vec.s / vec.t / vec.p / vec.q Comme un tableau : vec[0] / vec[1] / vec[2] / vec[3]
Accès identique : Créé Accès identique : Créé pour des questions de lisibilitépour des questions de lisibilitéposition, couleur, textureposition, couleur, texture
67
GLSL : Types
Matrices♦ mat2, mat3, mat4 : Matrice 2x2, 3x3 et 4x4 de float♦ Organisé en colonne♦ Accès aux colonnes d’une matrice mat :
mat[0] / mat[1] / mat[2] / mat[3] : 1, 2, 3 et 4ème colonne♦ Accès à un élément de mat :
mat[0][2] : 3ème élément de la 1ère colonne
Sampler♦ Type permettant un accès à une texture♦ Ne demande aucune connaissance de la façon dont est
définie la texture♦ Le shader ne peut définir de Sampler. Il les récupère
directement de l’application.
68
GLSL : Types
Sampler♦ Ne peut être modifié par le shader♦ Les différents types :
sampler1D : accès à une texture 1D sampler2D : accès à une texture 2D sampler3D : accès à une texture 3D samplerCube : accès à une texture cubique sampler1DShadow : accès à une texture 1D de profondeur avec
comparaison des profondeurs Sampler2DShadow : idem avec une texture 2D
69
GLSL : structures
TableauxDéclarés classiquement :La taille est optionnelle, peut être calculée à la
compilation :
Redimensionnement explicite ou implicite illégal :
typetype nomnom[[tailletaille]];;typetype nomnom[[tailletaille]];;
vec4 pts[];vec4 pts[];pts[0] = vec4(0,0,0,0);pts[0] = vec4(0,0,0,0);pts[6] = vec4(1,0,0,0);pts[6] = vec4(1,0,0,0);// pts est de taille 7// pts est de taille 7
vec4 pts[];vec4 pts[];pts[0] = vec4(0,0,0,0);pts[0] = vec4(0,0,0,0);pts[6] = vec4(1,0,0,0);pts[6] = vec4(1,0,0,0);// pts est de taille 7// pts est de taille 7
vec4 pts[];vec4 pts[];vec4 pts[10];vec4 pts[10];vec4 pts[20]; // Illégalvec4 pts[20]; // Illégalpts[20] = vec4(0,0,0,0); // Illégalpts[20] = vec4(0,0,0,0); // Illégal
vec4 pts[];vec4 pts[];vec4 pts[10];vec4 pts[10];vec4 pts[20]; // Illégalvec4 pts[20]; // Illégalpts[20] = vec4(0,0,0,0); // Illégalpts[20] = vec4(0,0,0,0); // Illégal
70
GLSL : structures
StructureSyntaxe :
Exemple :
Peuvent être emboîtées et encapsuléesPeuvent contenir tous les types précédentsS’utilisent directement sans le mot clé structstruct
structstruct nom_structurenom_structure {{ type champstype champs;;}}
structstruct nom_structurenom_structure {{ type champstype champs;;}}
structstruct kernel3x3 kernel3x3 {{ sizesize ponderation; ponderation; floatfloat coef[9]; coef[9];}}
structstruct kernel3x3 kernel3x3 {{ sizesize ponderation; ponderation; floatfloat coef[9]; coef[9];}}
kernel3x3 blur;kernel3x3 blur;kernel3x3 blur;kernel3x3 blur;
71
GLSL : constructeurs
« Constructeurs » (initialisation)Scalaire : comme en C :Autres types : utilisation de constructeur
♦ Similaire à un appel de fonction♦ Autant d’argument que de valeur à initialiser♦ Exemple :
♦ Cas particulier : Constructeur vecteur avec 1 float : remplissage Constructeur matrice avec 1 float : matrice diagonale
float a,b=3.0,c;float a,b=3.0,c;float a,b=3.0,c;float a,b=3.0,c;
vec4 v = vec4(1.0,2.0,0.0,1.0);vec4 v = vec4(1.0,2.0,0.0,1.0);kernel3x3 blur = blur(1./9.,{0.0f});kernel3x3 blur = blur(1./9.,{0.0f});vec4 v = vec4(1.0,2.0,0.0,1.0);vec4 v = vec4(1.0,2.0,0.0,1.0);kernel3x3 blur = blur(1./9.,{0.0f});kernel3x3 blur = blur(1./9.,{0.0f});
72
GLSL : conversions
Conversions :vers bool : 0 ou 0.0 => false sinon truede bool : false => 0 / true => 1Vecteur à Vecteur :
♦ La source doit avoir un nombre de composante > destination
♦ Affectation dans l’ordre. Les termes restants ne sont pas utilisés
Vecteur à Matrice :♦ Remplissage dans l’ordre de la matrice (colonne major)
Matrice à Matrice :♦ Lecture, remplissage en colonne major
73
GLSL : qualifiers
Qualificatifs de variables (qualifiers) : attribute :
♦ Variables correspondant à ce qui est injecté fréquemment dans le pipe line : sommets, normales …
♦ Accessible en lecture uniquement♦ Réservé au vertex program♦ Sont forcément des flottants : float, vecteur ou matrice♦ Certaines variables prédéfinies
uniform :♦ Variables correspondant à des données ne changeant pas fréquemment (au
maximum 1 fois par primitive)♦ Accessible en lecture uniquement♦ Certaines variables prédéfinies♦ Commun aux vertex et fragment program
74
GLSL : qualifiers
Qualificatifs de variables (qualifiers) :varying :
♦ Interface entre le vertex program et le fragment program♦ Accessible en écriture dans le vertex shader♦ Accessible en lecture dans le fragment shader♦ Interpolation entre le vertex et le fragment sur la
primitiveconst :
♦ Constante : initialisation obligatoire et accessible en lecture
sans qualificateur :♦ Variable temporaire : accessible en lecture et écriture♦ Défini pour un program donné (vertex ou fragment)
75
GLSL : flux de données
Les vertex program :prédéfinies prédéfinies
gl_Vertex, gl_Normal …gl_Vertex, gl_Normal …
VERTEXVERTEXPROGRAMPROGRAM
prédéfiniesprédéfiniesgl_ModelViewMatrixgl_ModelViewMatrixgl_LightSource[0..n]gl_LightSource[0..n]
prédéfiniesprédéfiniesgl_FrontColorgl_FrontColor
gl_FogFragColorgl_FogFragColor
définies pardéfinies parutilisateurutilisateur AttributeAttribute
définiesdéfiniespar l’utilisateurpar l’utilisateur
UniformUniform
spéciales :spéciales :gl_Position, gl_PointSizegl_Position, gl_PointSize
gl_ClipVertexgl_ClipVertex
définiesdéfiniespar par
l’utilisateurl’utilisateurVaryingVarying
TexturesTextures
76
GLSL : flux de données
Fragment program
FRAGMENTFRAGMENTPROGRAMPROGRAM
SpécialesSpécialesgl_FragColor, gl_FragDepthgl_FragColor, gl_FragDepth
prédéfiniesprédéfiniesgl_Colorgl_Color
gl_TexCoord[0..n]gl_TexCoord[0..n]
spéciales :spéciales :gl_FragCoordgl_FragCoord
gl_FrontFacinggl_FrontFacing
définiesdéfiniespar par
l’utilisateurl’utilisateurVaryingVarying
prédéfiniesprédéfiniesgl_ModelViewMatrixgl_ModelViewMatrixgl_LightSource[0..n]gl_LightSource[0..n]
définiesdéfiniespar l’utilisateurpar l’utilisateur
UniformUniform
TexturesTextures
77
GLSL : flux d'instructions
Chaque programme possède un main Quasiment strictement identique au C
if…else / while / do … while / forbreak / continuePas de switch, pas de goto
Fonctions : identique au C saufPassage par valeur et référence : qualificateurs
♦ in : passage par valeur♦ out : accessible en écriture seulement (copié à la fin)♦ inout : passage par référence (copié au début et à la fin)♦ const : ne peut être écrit, utilisable uniquement avec in
78
GLSL : opérations
Similaires à celles du CArithmétiques : +, -, *, /Logiques : &&, ||, ^^, !, <, >, <=, >=, ==, !=Affectation : =, +=, -=, *=, /=, ++, --Sélection : ., [], ?:
Opérations sur les vecteurs & matricesPas d’opérateur logique (fonctions prédéfinies)Opérations composant par composant SAUF :
♦ vecteur * matrice : transposée du vecteur fois la matrice♦ matrice * vecteur : l’opération classique matrice vecteur
79
GLSL : opérations
Sélection composantes d’un vecteur : swizlingTrois groupes de sélection : xyzw, rgba ou stpqOn peut les composer / ordonner / restreindre à
loisir
vec4 v = vec4(1.0,2.0,0.0,3.0);vec4 v = vec4(1.0,2.0,0.0,3.0);v4.rgba; // vecteur à 4 composantes identique à v4v4.rgba; // vecteur à 4 composantes identique à v4v4.xy; // vecteur à 2 composantes (1.0,2.0)v4.xy; // vecteur à 2 composantes (1.0,2.0)v4.psq; // vecteur à 3 composantes (0.0,1.0,3.0)v4.psq; // vecteur à 3 composantes (0.0,1.0,3.0)v4.g; // C’est un floatv4.g; // C’est un floatv4.xyba; // Illégalv4.xyba; // Illégalvec4 dup=v4.rraa; // dup = vec4(1.0,1.0,3.0,3.0)vec4 dup=v4.rraa; // dup = vec4(1.0,1.0,3.0,3.0)dup.xzyw = v4.xxzz;// dup = vec4(1.0,0.0,1.0,0.0)dup.xzyw = v4.xxzz;// dup = vec4(1.0,0.0,1.0,0.0)dup.xxzz = v4; // Illégaldup.xxzz = v4; // Illégal
vec4 v = vec4(1.0,2.0,0.0,3.0);vec4 v = vec4(1.0,2.0,0.0,3.0);v4.rgba; // vecteur à 4 composantes identique à v4v4.rgba; // vecteur à 4 composantes identique à v4v4.xy; // vecteur à 2 composantes (1.0,2.0)v4.xy; // vecteur à 2 composantes (1.0,2.0)v4.psq; // vecteur à 3 composantes (0.0,1.0,3.0)v4.psq; // vecteur à 3 composantes (0.0,1.0,3.0)v4.g; // C’est un floatv4.g; // C’est un floatv4.xyba; // Illégalv4.xyba; // Illégalvec4 dup=v4.rraa; // dup = vec4(1.0,1.0,3.0,3.0)vec4 dup=v4.rraa; // dup = vec4(1.0,1.0,3.0,3.0)dup.xzyw = v4.xxzz;// dup = vec4(1.0,0.0,1.0,0.0)dup.xzyw = v4.xxzz;// dup = vec4(1.0,0.0,1.0,0.0)dup.xxzz = v4; // Illégaldup.xxzz = v4; // Illégal
80
GPGPU
3. GPGPU on the GPU3.3 Lien avec l'application
81
Shader & pipeline
Le lien se fait par les variables ! L’application envoie dans le pipe line :
Des primitives : constituées de vertex ou données♦ Ce seront les variables attribute
L’état de la machine OpenGL :♦ Variables prédéfinies comme les lumières ou la couleur
du brouillard♦ Variables définies par l’application♦ Ce sont les variables uniform
82
Shader & pipeline
Vertex ShaderRemplace complètement le pipe line classiqueVariables attribute prédéfinies :
♦ Reçue par des appels standard à des fonctions OpenGL♦ Prédéfinies :
gl_Position : correspond à glVertex3f(…) gl_Normal : correspond à glNormal3f(…) gl_Color : correspond à glColor3f(…) gl_SecondaryColor : correspond à glSecondaryColor3f(…) gl_MultiTexCoord0 :
correspond à glTexCoord2f(…) / glMultiTexCoord(…) …
83
Shader & pipeline
Vertex ShaderVariables attribute définies par l’utilisateur :
♦ Utilisation de glVertexAttribARB♦ Voir dans la partie suivante
Variables uniform prédéfinies♦ Cf. ci-après
Variable uniform définies par l’utilisateur♦ Utilisation de glUniformARB♦ Voir dans la partie suivante
84
Shader & pipeline
Vertex ShaderVariables varying spéciales :
♦ Variable gl_Position Doit impérativement être écrite C’est un vec4
♦ Variable gl_PointSize Taille du point : optionnel C’est un float
♦ Variable gl_ClipVertex Coordonnées du point pour le clipping : optionnel C’est un vec4
85
Shader & pipeline
Vertex ShaderVariables varying prédéfinies :
♦ vec4 gl_FrontColor♦ vec4 gl_BackColor♦ vec4 gl_FrontSecondaryColor♦ vec4 gl_BackSecondaryColor♦ vec4 gl_TexCoord[0..n]♦ float gl_FogFragCoord
Variables varying définies par l’utilisateur♦ Rien à faire coté application. Tout est géré dans le driver
86
Shader & pipeline
Fragment ShaderLes varying arrivent après interpolation
perspectiveVariables varying spéciales :
♦ vec4 gl_FragCoord : Position du fragment
♦ bool gl_FrontFacing : La primitive du fragment est elle face à la caméra
Variables varying prédéfinies : ♦ vec4 gl_SecondaryColor♦ vec4 gl_Color♦ vec4 gl_TexCoord[0..n]♦ float gl_FogFragCoord
87
Shader & pipeline
Fragment ShaderVariables uniform : comme pour le vertex shaderVariables de sorties :
♦ vec4 gl_FragColor : Couleur du fragment à ajouter dans l’image
♦ float gl_FragDepth : Permet de fixer la profondeur du fragment Si non fixé, on conserve la valeur de base
88
Shader & pipeline
Variables uniformes prédéfiniesIl y en a énormément :
♦ Pour les lumières♦ Pour le brouillard♦ Pour les matrices de transformation♦ Pour les paramètres de la caméra♦ Pour les matériaux utilisés par les objets♦ Pour les propriétés de point ♦ …
Correspondent à des « états » du pipeline graphique
Liste complète :
89
// VERTEX PROGRAM (tiré du ‘Orange Book’)// VERTEX PROGRAM (tiré du ‘Orange Book’)uniformuniform float CoolestTemp; float CoolestTemp;uniformuniform float tempRange; float tempRange;
attributeattribute float vertexTemp; float vertexTemp;
varyingvarying float Temperature; float Temperature;
void main() {void main() { // Calcule le degre de temperature entre 0 et 1// Calcule le degre de temperature entre 0 et 1 TemperatureTemperature = ( = (vertexTempvertexTemp - - CoolestTempCoolestTemp)/)/tempRangetempRange;; gl_Positiongl_Position = = gl_ModelViewProjectionMatrixgl_ModelViewProjectionMatrix * * gl_Vertexgl_Vertex;;}}
// VERTEX PROGRAM (tiré du ‘Orange Book’)// VERTEX PROGRAM (tiré du ‘Orange Book’)uniformuniform float CoolestTemp; float CoolestTemp;uniformuniform float tempRange; float tempRange;
attributeattribute float vertexTemp; float vertexTemp;
varyingvarying float Temperature; float Temperature;
void main() {void main() { // Calcule le degre de temperature entre 0 et 1// Calcule le degre de temperature entre 0 et 1 TemperatureTemperature = ( = (vertexTempvertexTemp - - CoolestTempCoolestTemp)/)/tempRangetempRange;; gl_Positiongl_Position = = gl_ModelViewProjectionMatrixgl_ModelViewProjectionMatrix * * gl_Vertexgl_Vertex;;}}
// FRAGMENT PROGRAM (tiré du ‘Orange Book’)// FRAGMENT PROGRAM (tiré du ‘Orange Book’)uniformuniform vec3 CoolestColor; vec3 CoolestColor;uniformuniform vec3 HottestColor; vec3 HottestColor;
varyingvarying float Temperature; float Temperature;
void main() {void main() { // Utilisation d’une fonction prédéfinie : mix// Utilisation d’une fonction prédéfinie : mix // afin de trouver une couleur mélangée// afin de trouver une couleur mélangée vec3 color = vec3 color = mixmix((CoolestColorCoolestColor,,HottestColorHottestColor,,TemperatureTemperature);); gl_FragColorgl_FragColor = = vec4vec4(color,1.0); (color,1.0); }}
// FRAGMENT PROGRAM (tiré du ‘Orange Book’)// FRAGMENT PROGRAM (tiré du ‘Orange Book’)uniformuniform vec3 CoolestColor; vec3 CoolestColor;uniformuniform vec3 HottestColor; vec3 HottestColor;
varyingvarying float Temperature; float Temperature;
void main() {void main() { // Utilisation d’une fonction prédéfinie : mix// Utilisation d’une fonction prédéfinie : mix // afin de trouver une couleur mélangée// afin de trouver une couleur mélangée vec3 color = vec3 color = mixmix((CoolestColorCoolestColor,,HottestColorHottestColor,,TemperatureTemperature);); gl_FragColorgl_FragColor = = vec4vec4(color,1.0); (color,1.0); }}
Exemple de shader
90
Utilisation des shaders
Comment utiliser les shader dans une application OpenGL ?Utilisation des API :
♦ GLSL_vertex_program♦ GLSL_fragment_program
Collection de fonction en C (fourni par les drivers de votre carte) permettant de :
♦ Créer les vertex / fragment shader (vide)♦ Les remplir avec du code en provenance d’un fichier♦ Compiler (à l’utilisation donc !), attacher, lier ces
programmes♦ Envoyer des données aux shaders
91
Utilisation des shaders
Méthode :1. Créer un ou plusieurs shaders
♦ glCreateShaderObject2. Leur donner du code source
♦ glShaderSource3. Les compiler
♦ glCompileShader4. Créer un objet programme
♦ glCreateProgramObject5. Attacher les shaders à cet objet
♦ glAttachObject
92
Utilisation des shaders
Méthode :6. Lier le programme
♦ Permet par exemple de relier les variables varying …♦ Similaire à la phase de lien d’une phase de compilation♦ glLinkProgram
7. Intégrer le programme dans le pipeline graphique
♦ glUseProgramObject8. Fournir les variables définies par l’utilisateur
♦ glGetUniformLocation, glUniform♦ glBindAttribLocation, glGetAttribLocation, glVertexAttrib♦ glEnableVertexAttribArray, glVertexAttribPointer
93
GLhandleARB loadShaders(const char *vertexFile,const char *fragmentFile) {GLhandleARB loadShaders(const char *vertexFile,const char *fragmentFile) {
GLhandleARB programObject;GLhandleARB programObject; // CREATION DU PROGRAMME// CREATION DU PROGRAMME programObject = programObject = glCreateProgramObjectglCreateProgramObject();(); if(!programObject) return 0;if(!programObject) return 0;
// CHARGEMENT DU VERTEX SHADER :// CHARGEMENT DU VERTEX SHADER : char *vertexSource;char *vertexSource; // Récupération de la chaine de caractère du fichier d’entree// Récupération de la chaine de caractère du fichier d’entree if (!if (!loadSourceloadSource(vertexFile, &vertexSource)) return 0;(vertexFile, &vertexSource)) return 0; // Creation d'un objet qui va contenir des sources// Creation d'un objet qui va contenir des sources GLhandleARB shaderObject = GLhandleARB shaderObject = glCreateShaderObjectglCreateShaderObject(GL_VERTEX_SHADER_ARB);(GL_VERTEX_SHADER_ARB); // Association des sources// Association des sources glShaderSourceglShaderSource(shaderObject, 1, & vertexSource, NULL);(shaderObject, 1, & vertexSource, NULL); // Compilation des sources// Compilation des sources glCompileShaderglCompileShader(shaderObject);(shaderObject); // Attachement au programme// Attachement au programme glAttachObjectglAttachObject(programObject, shaderObject);(programObject, shaderObject); // Destruction de l’objet shader (inutile maintenant)// Destruction de l’objet shader (inutile maintenant) glDeleteObjectglDeleteObject(shaderObject);(shaderObject);
......
GLhandleARB loadShaders(const char *vertexFile,const char *fragmentFile) {GLhandleARB loadShaders(const char *vertexFile,const char *fragmentFile) {
GLhandleARB programObject;GLhandleARB programObject; // CREATION DU PROGRAMME// CREATION DU PROGRAMME programObject = programObject = glCreateProgramObjectglCreateProgramObject();(); if(!programObject) return 0;if(!programObject) return 0;
// CHARGEMENT DU VERTEX SHADER :// CHARGEMENT DU VERTEX SHADER : char *vertexSource;char *vertexSource; // Récupération de la chaine de caractère du fichier d’entree// Récupération de la chaine de caractère du fichier d’entree if (!if (!loadSourceloadSource(vertexFile, &vertexSource)) return 0;(vertexFile, &vertexSource)) return 0; // Creation d'un objet qui va contenir des sources// Creation d'un objet qui va contenir des sources GLhandleARB shaderObject = GLhandleARB shaderObject = glCreateShaderObjectglCreateShaderObject(GL_VERTEX_SHADER_ARB);(GL_VERTEX_SHADER_ARB); // Association des sources// Association des sources glShaderSourceglShaderSource(shaderObject, 1, & vertexSource, NULL);(shaderObject, 1, & vertexSource, NULL); // Compilation des sources// Compilation des sources glCompileShaderglCompileShader(shaderObject);(shaderObject); // Attachement au programme// Attachement au programme glAttachObjectglAttachObject(programObject, shaderObject);(programObject, shaderObject); // Destruction de l’objet shader (inutile maintenant)// Destruction de l’objet shader (inutile maintenant) glDeleteObjectglDeleteObject(shaderObject);(shaderObject);
......
Utilisation des shaders
94
...... // CHARGEMENT DU FRAGMENT SHADER :// CHARGEMENT DU FRAGMENT SHADER : char *fragmentSource;char *fragmentSource; // Récupération de la chaine de caractère du fichier d’entree// Récupération de la chaine de caractère du fichier d’entree if (!if (!loadSourceloadSource(fragmentFile, &fragmentSource)) return 0;(fragmentFile, &fragmentSource)) return 0; // Creation d'un objet qui va contenir des sources// Creation d'un objet qui va contenir des sources shaderObject = shaderObject = glCreateShaderObjectglCreateShaderObject(GL_FRAGMENT_SHADER_ARB);(GL_FRAGMENT_SHADER_ARB); // Association des sources// Association des sources glShaderSourceglShaderSource(shaderObject, 1, & fragmentSource, NULL);(shaderObject, 1, & fragmentSource, NULL); // Compilation des sources// Compilation des sources glCompileShaderglCompileShader(shaderObject);(shaderObject); // Attachement au programme// Attachement au programme glAttachObjectglAttachObject(programObject, shaderObject);(programObject, shaderObject); // Destruction de l’objet shader (inutile maintenant)// Destruction de l’objet shader (inutile maintenant) glDeleteObjectglDeleteObject(shaderObject);(shaderObject);
// Linkage du programme// Linkage du programme glLinkProgramglLinkProgram(programObject);(programObject);}}// PLUS TARD DANS L'INITIALISATION// PLUS TARD DANS L'INITIALISATIONsProg = loadShaders(sProg = loadShaders("vert.vert","fragtxt.frag");"vert.vert","fragtxt.frag");// PLUS TARD DANS LA FONCTION DE DESSIN ...// PLUS TARD DANS LA FONCTION DE DESSIN ...glUseProgramglUseProgram(sProg); (sProg); // si =0 on garde le pipeline classique// si =0 on garde le pipeline classique
...... // CHARGEMENT DU FRAGMENT SHADER :// CHARGEMENT DU FRAGMENT SHADER : char *fragmentSource;char *fragmentSource; // Récupération de la chaine de caractère du fichier d’entree// Récupération de la chaine de caractère du fichier d’entree if (!if (!loadSourceloadSource(fragmentFile, &fragmentSource)) return 0;(fragmentFile, &fragmentSource)) return 0; // Creation d'un objet qui va contenir des sources// Creation d'un objet qui va contenir des sources shaderObject = shaderObject = glCreateShaderObjectglCreateShaderObject(GL_FRAGMENT_SHADER_ARB);(GL_FRAGMENT_SHADER_ARB); // Association des sources// Association des sources glShaderSourceglShaderSource(shaderObject, 1, & fragmentSource, NULL);(shaderObject, 1, & fragmentSource, NULL); // Compilation des sources// Compilation des sources glCompileShaderglCompileShader(shaderObject);(shaderObject); // Attachement au programme// Attachement au programme glAttachObjectglAttachObject(programObject, shaderObject);(programObject, shaderObject); // Destruction de l’objet shader (inutile maintenant)// Destruction de l’objet shader (inutile maintenant) glDeleteObjectglDeleteObject(shaderObject);(shaderObject);
// Linkage du programme// Linkage du programme glLinkProgramglLinkProgram(programObject);(programObject);}}// PLUS TARD DANS L'INITIALISATION// PLUS TARD DANS L'INITIALISATIONsProg = loadShaders(sProg = loadShaders("vert.vert","fragtxt.frag");"vert.vert","fragtxt.frag");// PLUS TARD DANS LA FONCTION DE DESSIN ...// PLUS TARD DANS LA FONCTION DE DESSIN ...glUseProgramglUseProgram(sProg); (sProg); // si =0 on garde le pipeline classique// si =0 on garde le pipeline classique
Utilisation des shaders
95
Utilisation des shaders
Transmission des variables uniform :Variables prédéfinies :
♦ Utiliser les instructions classiques OpenGLVariables définies par l’utilisateur
♦ Récupération de l’indice de stockage du driver : glGetUniformLocation(program, "nom_variable")
♦ Envoi des valeurs à cette variable : glUniform{1|2|3|4}{s|f|v}{v} (indice,{nb,} valeur)
Transmission des variables attribute :Variables prédéfinies :
♦ Utilisation glVertex pour gl_Vertex♦ Utilisation glNormal pour gl_Normal …
96
Utilisation des shaders
Variables définies par l’utilisateur :♦ Récupérer l’indice de stockage de la variable :
ind = glGetAttribLocation(program, "nom_variable" ); ind = glBindAttribLocation(program,1, "nom_variable" );
♦ Envoyer les valeurs : Une valeur : glVertexAttrib{1234}{s|f|d}{v}(indice,valeur);
D’autres combinaisons existent (avec 4) Par vertex array :
glEnableVertexAttribArray(indice)glVertexAttribPointer(indice, size, type, normalized,
stride, pointeur);
97
GPGPU
3. GPGPU on the GPU3.4 Conseils & optimisations
98
Conseils
Avoir une idée claire de ce que l’on veutOù le shader intervient-il dans cela ?
Ajouter la complexité progressivementCommencer par les choses simplesTester et complexifierMettre des commentaires sur les choses qui
marchent Faire au plus simple Faire au plus modulaire
Utiliser des fonctionsIl est préférable de faire une bibliothèque de
shaders simples qu’un grand shader gérant tout !
99
Conseils
Faire une bonne répartition des calculs entreCPU
♦ Précalcul dans des textures♦ Si le CPU est dispo : l’utiliser !
Vertex shader♦ Pour toute donnée variant peu dans l’image
Fragment shader♦ Seulement pour des données variant beaucoup et non
linéairement !
Enlever toutes les opérations non nécessaires
100
Optimisations
Utilisez les fonctions prédéfiniesListe accessible sur :
Utiliser les vecteursType native des processeurs électroniques
Utiliser des texturesPour encoder des fonctions complexes de 1,2 ou 3
variables
http://developer.3dlabs.com/documents/index.htmhttp://developer.3dlabs.com/documents/index.htm
101
GPGPU
3. GPGPU on the GPU3.4 Exemples simples
102
Exemples simples
Application d’une texture// [Vertex_Shader] // [Vertex_Shader] void main() { void main() {
gl_TexCoord[0] = gl_MultiTexCoord0; gl_TexCoord[0] = gl_MultiTexCoord0; gl_Position = ftransform(); gl_Position = ftransform();
} }
// [Vertex_Shader] // [Vertex_Shader] void main() { void main() {
gl_TexCoord[0] = gl_MultiTexCoord0; gl_TexCoord[0] = gl_MultiTexCoord0; gl_Position = ftransform(); gl_Position = ftransform();
} }
// [Fragment_Shader] // [Fragment_Shader] uniform sampler2D colorMap; uniform sampler2D colorMap; void main (void) { void main (void) {
gl_FragColor = texture2D( colorMap, gl_TexCoord[0].st); gl_FragColor = texture2D( colorMap, gl_TexCoord[0].st); }}
// [Fragment_Shader] // [Fragment_Shader] uniform sampler2D colorMap; uniform sampler2D colorMap; void main (void) { void main (void) {
gl_FragColor = texture2D( colorMap, gl_TexCoord[0].st); gl_FragColor = texture2D( colorMap, gl_TexCoord[0].st); }}
// Dans le code source : initialisation// Dans le code source : initialisationglActiveTextureARB(GL_TEXTURE0_ARB) ;glActiveTextureARB(GL_TEXTURE0_ARB) ;glEnable(GL_TEXTURE_2D);glEnable(GL_TEXTURE_2D);glBindTexture(GL_TEXTURE_2D,tex_id );glBindTexture(GL_TEXTURE_2D,tex_id );glTexImage2D(GL_TEXTURE_2D, 0, 3, width, height, 0, GL_RGB,glTexImage2D(GL_TEXTURE_2D, 0, 3, width, height, 0, GL_RGB,GL_UNSIGNED_BYTE, (const GLvoid *)texData) ;GL_UNSIGNED_BYTE, (const GLvoid *)texData) ;glBindTexture(GL_TEXTURE_2D,0);glBindTexture(GL_TEXTURE_2D,0);
// Dans la fonction display// Dans la fonction displayglUniform1i(glGetUniformLocation(shadprg,"colorMap"),0) ;glUniform1i(glGetUniformLocation(shadprg,"colorMap"),0) ;glBindTexture(GL_TEXTURE_2D, tex_id);glBindTexture(GL_TEXTURE_2D, tex_id);
// Dans le code source : initialisation// Dans le code source : initialisationglActiveTextureARB(GL_TEXTURE0_ARB) ;glActiveTextureARB(GL_TEXTURE0_ARB) ;glEnable(GL_TEXTURE_2D);glEnable(GL_TEXTURE_2D);glBindTexture(GL_TEXTURE_2D,tex_id );glBindTexture(GL_TEXTURE_2D,tex_id );glTexImage2D(GL_TEXTURE_2D, 0, 3, width, height, 0, GL_RGB,glTexImage2D(GL_TEXTURE_2D, 0, 3, width, height, 0, GL_RGB,GL_UNSIGNED_BYTE, (const GLvoid *)texData) ;GL_UNSIGNED_BYTE, (const GLvoid *)texData) ;glBindTexture(GL_TEXTURE_2D,0);glBindTexture(GL_TEXTURE_2D,0);
// Dans la fonction display// Dans la fonction displayglUniform1i(glGetUniformLocation(shadprg,"colorMap"),0) ;glUniform1i(glGetUniformLocation(shadprg,"colorMap"),0) ;glBindTexture(GL_TEXTURE_2D, tex_id);glBindTexture(GL_TEXTURE_2D, tex_id);
103
Exemples simples
Phong lighting// [Vertex_Shader]// [Vertex_Shader]
varying vec3 normal, lightDir, eyeVec;varying vec3 normal, lightDir, eyeVec;void main()void main(){{
normal = gl_NormalMatrix * gl_Normal;normal = gl_NormalMatrix * gl_Normal;vec3 vVertex = vec3(gl_ModelViewMatrix * gl_Vertex);vec3 vVertex = vec3(gl_ModelViewMatrix * gl_Vertex);lightDir = vec3(gl_LightSource[0].position.xyz - vVertex);lightDir = vec3(gl_LightSource[0].position.xyz - vVertex);eyeVec = -vVertex;eyeVec = -vVertex;gl_Position = ftransform();gl_Position = ftransform();
}}
// [Vertex_Shader]// [Vertex_Shader]
varying vec3 normal, lightDir, eyeVec;varying vec3 normal, lightDir, eyeVec;void main()void main(){{
normal = gl_NormalMatrix * gl_Normal;normal = gl_NormalMatrix * gl_Normal;vec3 vVertex = vec3(gl_ModelViewMatrix * gl_Vertex);vec3 vVertex = vec3(gl_ModelViewMatrix * gl_Vertex);lightDir = vec3(gl_LightSource[0].position.xyz - vVertex);lightDir = vec3(gl_LightSource[0].position.xyz - vVertex);eyeVec = -vVertex;eyeVec = -vVertex;gl_Position = ftransform();gl_Position = ftransform();
}}
104
Exemples simples
// [Fragment_Shader]// [Fragment_Shader]varying vec3 normal, lightDir, eyeVec;varying vec3 normal, lightDir, eyeVec;void main (void) {void main (void) {
vec4 final_color = vec4 final_color = (gl_FrontLightModelProduct.sceneColor * gl_FrontMaterial.ambient) + (gl_FrontLightModelProduct.sceneColor * gl_FrontMaterial.ambient) + (gl_LightSource[0].ambient * gl_FrontMaterial.ambient);(gl_LightSource[0].ambient * gl_FrontMaterial.ambient);vec3 N = normalize(normal);vec3 N = normalize(normal);vec3 L = normalize(lightDir);vec3 L = normalize(lightDir);float lambertTerm = dot(N,L);float lambertTerm = dot(N,L);if(lambertTerm > 0.0) {if(lambertTerm > 0.0) {
final_color += gl_LightSource[0].diffuse * final_color += gl_LightSource[0].diffuse * gl_FrontMaterial.diffuse * gl_FrontMaterial.diffuse *
lambertTerm;lambertTerm;vec3 E = normalize(eyeVec);vec3 E = normalize(eyeVec);vec3 R = reflect(-L, N);vec3 R = reflect(-L, N);float specular = pow( max(dot(R, E), 0.0), float specular = pow( max(dot(R, E), 0.0), gl_FrontMaterial.shininess );gl_FrontMaterial.shininess );final_color += gl_LightSource[0].specular * final_color += gl_LightSource[0].specular * gl_FrontMaterial.specular * gl_FrontMaterial.specular *
specular;specular;}}gl_FragColor = final_color;gl_FragColor = final_color;
}}
// [Fragment_Shader]// [Fragment_Shader]varying vec3 normal, lightDir, eyeVec;varying vec3 normal, lightDir, eyeVec;void main (void) {void main (void) {
vec4 final_color = vec4 final_color = (gl_FrontLightModelProduct.sceneColor * gl_FrontMaterial.ambient) + (gl_FrontLightModelProduct.sceneColor * gl_FrontMaterial.ambient) + (gl_LightSource[0].ambient * gl_FrontMaterial.ambient);(gl_LightSource[0].ambient * gl_FrontMaterial.ambient);vec3 N = normalize(normal);vec3 N = normalize(normal);vec3 L = normalize(lightDir);vec3 L = normalize(lightDir);float lambertTerm = dot(N,L);float lambertTerm = dot(N,L);if(lambertTerm > 0.0) {if(lambertTerm > 0.0) {
final_color += gl_LightSource[0].diffuse * final_color += gl_LightSource[0].diffuse * gl_FrontMaterial.diffuse * gl_FrontMaterial.diffuse *
lambertTerm;lambertTerm;vec3 E = normalize(eyeVec);vec3 E = normalize(eyeVec);vec3 R = reflect(-L, N);vec3 R = reflect(-L, N);float specular = pow( max(dot(R, E), 0.0), float specular = pow( max(dot(R, E), 0.0), gl_FrontMaterial.shininess );gl_FrontMaterial.shininess );final_color += gl_LightSource[0].specular * final_color += gl_LightSource[0].specular * gl_FrontMaterial.specular * gl_FrontMaterial.specular *
specular;specular;}}gl_FragColor = final_color;gl_FragColor = final_color;
}}
105
Exemples simples : érosion 2D
// [Vertex_Shader]// [Vertex_Shader]varying vec4 owncoordinates;varying vec4 owncoordinates;varying vec4 gl_TexCoord[4]; // Inutile (variables prédéfinies)varying vec4 gl_TexCoord[4]; // Inutile (variables prédéfinies)uniform vec4 coeff_image;uniform vec4 coeff_image;/* Renvoie les 8-connexites suivantes .../* Renvoie les 8-connexites suivantes ...[1].zw[1].zw || [1].xy[1].xy || [0].zw[0].zw[2].xy[2].xy || XX || [0].xy[0].xy[2].zw[2].zw || [3].xy[3].xy || [3].zw[3].zw*/*/void main()void main(){{
// Recuperation de la position de la camera// Recuperation de la position de la cameraowncoordinates = gl_MultiTexCoord0;owncoordinates = gl_MultiTexCoord0;gl_TexCoord[0] = vec4(gl_MultiTexCoord0.x+coeff_image.x,gl_MultiTexCoord0.y,gl_TexCoord[0] = vec4(gl_MultiTexCoord0.x+coeff_image.x,gl_MultiTexCoord0.y,
gl_MultiTexCoord0.x+coeff_image.x,gl_MultiTexCoord0.ygl_MultiTexCoord0.x+coeff_image.x,gl_MultiTexCoord0.y +coeff_image.y);+coeff_image.y);
gl_TexCoord[1] = vec4(gl_MultiTexCoord0.x,gl_MultiTexCoord0.y+coeff_image.y,gl_TexCoord[1] = vec4(gl_MultiTexCoord0.x,gl_MultiTexCoord0.y+coeff_image.y, gl_MultiTexCoord0.x-coeff_image.x,gl_MultiTexCoord0.ygl_MultiTexCoord0.x-coeff_image.x,gl_MultiTexCoord0.y
+coeff_image.y);+coeff_image.y);gl_TexCoord[2] = vec4(gl_MultiTexCoord0.x-coeff_image.x,gl_MultiTexCoord0.y,gl_TexCoord[2] = vec4(gl_MultiTexCoord0.x-coeff_image.x,gl_MultiTexCoord0.y,
gl_MultiTexCoord0.x-coeff_image.x,gl_MultiTexCoord0.ygl_MultiTexCoord0.x-coeff_image.x,gl_MultiTexCoord0.y-coeff_image.y);-coeff_image.y);
gl_TexCoord[3] = vec4(gl_MultiTexCoord0.x,gl_TexCoord[3] = vec4(gl_MultiTexCoord0.x,gl_MultiTexCoord0.y-coeff_image.y,gl_MultiTexCoord0.y-coeff_image.y, gl_MultiTexCoord0.x+coeff_image.x,gl_MultiTexCoord0.ygl_MultiTexCoord0.x+coeff_image.x,gl_MultiTexCoord0.y
-coeff_image.y);-coeff_image.y);gl_Position = ftransform();gl_Position = ftransform();
}}
// [Vertex_Shader]// [Vertex_Shader]varying vec4 owncoordinates;varying vec4 owncoordinates;varying vec4 gl_TexCoord[4]; // Inutile (variables prédéfinies)varying vec4 gl_TexCoord[4]; // Inutile (variables prédéfinies)uniform vec4 coeff_image;uniform vec4 coeff_image;/* Renvoie les 8-connexites suivantes .../* Renvoie les 8-connexites suivantes ...[1].zw[1].zw || [1].xy[1].xy || [0].zw[0].zw[2].xy[2].xy || XX || [0].xy[0].xy[2].zw[2].zw || [3].xy[3].xy || [3].zw[3].zw*/*/void main()void main(){{
// Recuperation de la position de la camera// Recuperation de la position de la cameraowncoordinates = gl_MultiTexCoord0;owncoordinates = gl_MultiTexCoord0;gl_TexCoord[0] = vec4(gl_MultiTexCoord0.x+coeff_image.x,gl_MultiTexCoord0.y,gl_TexCoord[0] = vec4(gl_MultiTexCoord0.x+coeff_image.x,gl_MultiTexCoord0.y,
gl_MultiTexCoord0.x+coeff_image.x,gl_MultiTexCoord0.ygl_MultiTexCoord0.x+coeff_image.x,gl_MultiTexCoord0.y +coeff_image.y);+coeff_image.y);
gl_TexCoord[1] = vec4(gl_MultiTexCoord0.x,gl_MultiTexCoord0.y+coeff_image.y,gl_TexCoord[1] = vec4(gl_MultiTexCoord0.x,gl_MultiTexCoord0.y+coeff_image.y, gl_MultiTexCoord0.x-coeff_image.x,gl_MultiTexCoord0.ygl_MultiTexCoord0.x-coeff_image.x,gl_MultiTexCoord0.y
+coeff_image.y);+coeff_image.y);gl_TexCoord[2] = vec4(gl_MultiTexCoord0.x-coeff_image.x,gl_MultiTexCoord0.y,gl_TexCoord[2] = vec4(gl_MultiTexCoord0.x-coeff_image.x,gl_MultiTexCoord0.y,
gl_MultiTexCoord0.x-coeff_image.x,gl_MultiTexCoord0.ygl_MultiTexCoord0.x-coeff_image.x,gl_MultiTexCoord0.y-coeff_image.y);-coeff_image.y);
gl_TexCoord[3] = vec4(gl_MultiTexCoord0.x,gl_TexCoord[3] = vec4(gl_MultiTexCoord0.x,gl_MultiTexCoord0.y-coeff_image.y,gl_MultiTexCoord0.y-coeff_image.y, gl_MultiTexCoord0.x+coeff_image.x,gl_MultiTexCoord0.ygl_MultiTexCoord0.x+coeff_image.x,gl_MultiTexCoord0.y
-coeff_image.y);-coeff_image.y);gl_Position = ftransform();gl_Position = ftransform();
}}
106
Exemples simples
// [Vertex_Shader]// [Vertex_Shader]uniform sampler2D basetex;uniform sampler2D basetex;varying vec2 owncoordinates ;varying vec2 owncoordinates ;varying vec4 gl_TexCoord[4]; // Inutile (variables prédéfinies)varying vec4 gl_TexCoord[4]; // Inutile (variables prédéfinies)
void main()void main(){{
float cpt = 0.0;float cpt = 0.0;
gl_FragColor = vec4(0.0,0.0,0.0,1.0);gl_FragColor = vec4(0.0,0.0,0.0,1.0);
if (texture2D(basetex,owncoordinates.xy).r > 0.0) {if (texture2D(basetex,owncoordinates.xy).r > 0.0) {//CALCUL DES TEXTURES ...//CALCUL DES TEXTURES ...cpt += texture2D(basetex,gl_TexCoord[0].xy).r;cpt += texture2D(basetex,gl_TexCoord[0].xy).r;cpt += texture2D(basetex,gl_TexCoord[0].zw).r;cpt += texture2D(basetex,gl_TexCoord[0].zw).r;cpt += texture2D(basetex,gl_TexCoord[1].xy).r;cpt += texture2D(basetex,gl_TexCoord[1].xy).r;cpt += texture2D(basetex,gl_TexCoord[1].zw).r;cpt += texture2D(basetex,gl_TexCoord[1].zw).r;if (cpt == 4.0) gl_FragColor.r = 1.0;if (cpt == 4.0) gl_FragColor.r = 1.0;
}}}}
// [Vertex_Shader]// [Vertex_Shader]uniform sampler2D basetex;uniform sampler2D basetex;varying vec2 owncoordinates ;varying vec2 owncoordinates ;varying vec4 gl_TexCoord[4]; // Inutile (variables prédéfinies)varying vec4 gl_TexCoord[4]; // Inutile (variables prédéfinies)
void main()void main(){{
float cpt = 0.0;float cpt = 0.0;
gl_FragColor = vec4(0.0,0.0,0.0,1.0);gl_FragColor = vec4(0.0,0.0,0.0,1.0);
if (texture2D(basetex,owncoordinates.xy).r > 0.0) {if (texture2D(basetex,owncoordinates.xy).r > 0.0) {//CALCUL DES TEXTURES ...//CALCUL DES TEXTURES ...cpt += texture2D(basetex,gl_TexCoord[0].xy).r;cpt += texture2D(basetex,gl_TexCoord[0].xy).r;cpt += texture2D(basetex,gl_TexCoord[0].zw).r;cpt += texture2D(basetex,gl_TexCoord[0].zw).r;cpt += texture2D(basetex,gl_TexCoord[1].xy).r;cpt += texture2D(basetex,gl_TexCoord[1].xy).r;cpt += texture2D(basetex,gl_TexCoord[1].zw).r;cpt += texture2D(basetex,gl_TexCoord[1].zw).r;if (cpt == 4.0) gl_FragColor.r = 1.0;if (cpt == 4.0) gl_FragColor.r = 1.0;
}}}}
107
GPGPU
4. GPGPU via Cuda
108
Let the specialists talk...
A view on Cuda Tutorial of Nvidia...