GPGPU. Cours de MII 2



Documents pareils
M2-Images. Rendu Temps Réel - OpenGL 4 et compute shaders. J.C. Iehl. December 18, 2013

TPs Architecture des ordinateurs DUT Informatique - M4104c SUJETS. R. Raffin Aix-Marseille Université romain.raffin-at-univ-amu.fr

Synthèse d'images I. Venceslas BIRI IGM Université de Marne La

Utiliser une WebCam. Micro-ordinateurs, informations, idées, trucs et astuces

Once the installation is complete, you can delete the temporary Zip files..

RIE LE RENDU THEO. 2 e trim ÉTAPE DE FINITION BOÎTE DE DIALOGUE. remarques

Développement mobile MIDP 2.0 Mobile 3D Graphics API (M3G) JSR 184. Frédéric BERTIN

Introduction à CUDA.

Une bibliothèque de templates pour CUDA

Instructions pour mettre à jour un HFFv2 v1.x.yy v2.0.00

Instructions Mozilla Thunderbird Page 1

Introduction à MATLAB R

Exercices sur SQL server 2000

Génération de code binaire pour application multimedia : une approche au vol

EPREUVE OPTIONNELLE d INFORMATIQUE CORRIGE

lundi 3 août 2009 Choose your language What is Document Connection for Mac? Communautés Numériques L informatique à la portée du Grand Public

Rendu temps réel de mer et de nuages

Guide d'installation rapide TFM-560X YO.13

WEB page builder and server for SCADA applications usable from a WEB navigator

XtremWeb-HEP Interconnecting jobs over DG. Virtualization over DG. Oleg Lodygensky Laboratoire de l Accélérateur Linéaire


Table des matières PRESENTATION DU LANGAGE DS2 ET DE SES APPLICATIONS. Introduction

Editing and managing Systems engineering processes at Snecma

THÈSE. présentée à TÉLÉCOM PARISTECH. pour obtenir le grade de. DOCTEUR de TÉLÉCOM PARISTECH. Mention Informatique et Réseaux. par.

HSCS 6.4 : mieux appréhender la gestion du stockage en environnement VMware et service de fichiers HNAS Laurent Bartoletti Product Marketing Manager

Paxton. ins Net2 desktop reader USB

3615 SELFIE. HOW-TO / GUIDE D'UTILISATION

How to Login to Career Page

TABLE DES MATIERES A OBJET PROCEDURE DE CONNEXION

Application Form/ Formulaire de demande

Contents Windows

VTP. LAN Switching and Wireless Chapitre 4

Cours d Algorithmique-Programmation 2 e partie (IAP2): programmation 24 octobre 2007impérative 1 / 44 et. structures de données simples

Surveillance de Scripts LUA et de réception d EVENT. avec LoriotPro Extended & Broadcast Edition

Efficient Object Versioning for Object- Oriented Languages From Model to Language Integration

VMware ESX : Installation. Hervé Chaudret RSI - Délégation Centre Poitou-Charentes

MapReduce. Malo Jaffré, Pablo Rauzy. 16 avril 2010 ENS. Malo Jaffré, Pablo Rauzy (ENS) MapReduce 16 avril / 15

CEST POUR MIEUX PLACER MES PDF

Le passé composé. C'est le passé! Tout ça c'est du passé! That's the past! All that's in the past!

UML : Unified Modeling Language

Contrôle d'accès Access control. Notice technique / Technical Manual

Introduction à la Programmation Parallèle: MPI

StruxureWare Power Monitoring v7.0. La nouvelle génération en matière de logiciel de gestion complète d énergie

Get Instant Access to ebook Cest Maintenant PDF at Our Huge Library CEST MAINTENANT PDF. ==> Download: CEST MAINTENANT PDF

Outils d'analyse de la sécurité des réseaux. HADJALI Anis VESA Vlad

Software and Hardware Datasheet / Fiche technique du logiciel et du matériel

MELTING POTES, LA SECTION INTERNATIONALE DU BELLASSO (Association étudiante de lʼensaparis-belleville) PRESENTE :

Nouveautés printemps 2013

HAUTE DISPONIBILITÉ DE MACHINE VIRTUELLE AVEC HYPER-V 2012 R2 PARTIE CONFIGURATION OPENVPN SUR PFSENSE

THE EVOLUTION OF CONTENT CONSUMPTION ON MOBILE AND TABLETS

1. Structure d un programme C. 2. Commentaire: /*..texte */ On utilise aussi le commentaire du C++ qui est valable pour C: 3.

Cedric Dumoulin (C) The Java EE 7 Tutorial

Notice Technique / Technical Manual

INSTRUMENTS DE MESURE SOFTWARE. Management software for remote and/or local monitoring networks

SNMP for cloud Jean Parpaillon. SNMP4cloud - 1

DOCUMENTATION - FRANCAIS... 2

Gestion des prestations Volontaire

Face Recognition Performance: Man vs. Machine

Compléter le formulaire «Demande de participation» et l envoyer aux bureaux de SGC* à l adresse suivante :

EN UNE PAGE PLAN STRATÉGIQUE

Bases de programmation. Cours 5. Structurer les données

Stratégie DataCenters Société Générale Enjeux, objectifs et rôle d un partenaire comme Data4

ARDUINO DOSSIER RESSOURCE POUR LA CLASSE

MANUEL MARKETING ET SURVIE PDF

Lamia Oukid, Ounas Asfari, Fadila Bentayeb, Nadjia Benblidia, Omar Boussaid. 14 Juin 2013

APPENDIX 6 BONUS RING FORMAT

SERVEUR DÉDIÉ DOCUMENTATION

Master4Light. Caractérisation Optique et Electrique des Sources Lumineuses. Equipement 2-en-1 : source de courant et spectrophotomètre

as Architecture des Systèmes d Information

1.The pronouns me, te, nous, and vous are object pronouns.

Prénom : Matricule : Sigle et titre du cours Groupe Trimestre INF1101 Algorithmes et structures de données Tous H2004. Loc Jeudi 29/4/2004

Forthcoming Database

Plateforme Technologique Innovante. Innovation Center for equipment& materials

Frequently Asked Questions

Guide d installation Deco Drain inc. DD200

Mon Service Public - Case study and Mapping to SAML/Liberty specifications. Gaël Gourmelen - France Telecom 23/04/2007

Segmentation d'images à l'aide d'agents sociaux : applications GPU

Lesson Plan Physical Descriptions. belle vieille grande petite grosse laide mignonne jolie. beau vieux grand petit gros laid mignon

INTRODUCTION A JAVA. Fichier en langage machine Exécutable

WORKSHOP OBIEE 11g (version ) PRE-REQUIS:

INSTITUT MARITIME DE PREVENTION. For improvement in health and security at work. Created in 1992 Under the aegis of State and the ENIM

Quick Start Guide This guide is intended to get you started with Rational ClearCase or Rational ClearCase MultiSite.

Vers du matériel libre

Algorithmique et Programmation, IMA

PROJECT POUR LE SYSTÈME DE SURVEILLANCE PAR CAMERA BASÉ SUR TECHNOLOGIE AXIS, PANNEAUX SOLAIRES ET LUMIERE DU LEDS BLOC D APARTEMENT LAURIER.

Durée estimée :1 journée Date de la réalisation : Description Fournisseur Référence Nombre PU HT LM35CZ, LM35AZ LM35DZ

Package Contents. System Requirements. Before You Begin

Analyse de sécurité de logiciels système par typage statique

Dans une agence de location immobilière...

Programmer en JAVA. par Tama

Initiation au HPC - Généralités

that the child(ren) was/were in need of protection under Part III of the Child and Family Services Act, and the court made an order on

PACKZ System Requirements. Version: Version: Copyright 2015, PACKZ Software GmbH. 1

GIGABIT PCI DESKTOP ADAPTER DGE-530T. Quick Installation Guide+ Guide d installation+

Plan du cours Cours théoriques. 29 septembre 2014

REMBO Version 2.0. Mathrice 2004 DESCRIPTION MISE EN OEUVRE CONCLUSION.

CETTE FOIS CEST DIFFERENT PDF

Les structures de données. Rajae El Ouazzani

Structure d un programme et Compilation Notions de classe et d objet Syntaxe

Transcription:

GPGPU Cours de MII 2 1

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 2

GPGPU Plan 1. Introduction 2. Architecture 3. GPGPU on the GPU 4. GPGPU via Cuda 5. Exemple et optimisation 3

GPGPU 1. Introduction 4

History of 3D 5

History of 3D 6

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... 7

The way it uses to be... The fixed function pipeline 8

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) 9

The way it uses to be... Programmable pipeline 10

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 11

Examples (DX 11) Dynamic Ambient Occlusion and Indirect Lighting, Bunnell, GPU Gems II, 2005 Real-Time Approximate Sorting for Self Shadowing and Transparency in Hair Rendering, Sintornet al., I3D 2008 Fast Summed- Area Table Generation and its Applications, Hensley et al., Eurographics2005 12

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 13

Examples CUDA inside OptiX, NVIDIA 2008 RenderAnts: Interactive Reyes Rendering on GPUs, Zhou et al., ACM SIGGRAPH Asia CUDA inside 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 14al., ACM SIGGRAPH 2010

The way it will be... Render to Data Structures DX11 Atomics to global memory Gather/scatter to memory ( unordered access views Order independent transparency Capture all rendered fragments PixelShader5 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) 15

The way it will be... 16

GPU Programming? GPU stands for Graphics Processing Unit Simply It is the processor that resides on your graphics card. GPUs allow us to achieve the unprecedented graphics capabilities now available in games 17

CPU vs GPU Why use GPU? 18

CPU vs GPU A quiet revolution and potential build-up Calculation: Memory 367 GFLOPS vs. 32 GFLOPS 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 19

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. 20

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 21

Wealth of applications Data Analysis Motion Planning Voronoi Diagrams Particle Systems Force-field simulation Molecular Dynamics Graph Drawing Geometric Optimization Physical Simulation Matrix Multiplication Database queries Conjugate Gradient Sorting and Searching Range queries Image Processing Signal Processing Finance Optimization Planning Radar, Sonar, Oil Exploration and graphics too!!

Wealth of applications

GPU Programming? A Unifying theme: Streaming All 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 24

Stream programming? A stream is a sequence of data could be numbers, colors, RGBA vectors, A kernel is a (fragment) program runs on each element of a stream generating an output stream (pixel buffer) 25

Stream programming? Two main ways of doing stream programming The pure GPU way Using the graphic programmable pipeline Language : Cg, HLSL, GLSL The GPGPU way Using high level abstraction library Language : BrookGPU, CUDA, OpenCL 26

Stream program on GPU Kernel vertex/fragment Input stream stream of fragments or vertices or texture data Output stream frame program buffer or pixel buffer or texture Multiple kernels multi-pass rendering sequence on the GPU 27

Stream program on GPGPU Kernel User defined function Input stream Stream Output stream Stream of any data (float mainly) of any data (float mainly) Multiple kernels Multi-pass execution of kernel on the GPU with synchronization 28

Stream programming To program the GPU, one must think of it as a (parallel) stream processor. 29

GPGPU 2. Architecture 30

GPU Architecture Nomenclature : Kernel : treatment unit Thread Host : a single processing unit : application hardware (CPU) Device : coprocessor hardware (GPU) 31

Architecture GeForce 7800 GTX 8 Vertex Engines Z-Cull Triangle Setup/Raster Shader Instruction Dispatch Fragment Crossbar Memory Partition Memory Partition 24 Pixel Shaders 16 Raster Operation Pipelines Memory Partition Memory Partition 32

Architecture G80 graphic mode The future of GPU is programmable processing? Build the architecture around the processor Host Input Assembler Setup / Rstr / ZCull SP SP SP TF SP TF SP TF L1 SP SP L1 SP TF SP SP SP TF L1 L2 FB SP TF L1 L1 L2 FB Pixel Thread Issue SP TF L2 FB SP SP TF L1 L2 FB SP Geom Thread Issue L1 L2 FB Thread Processor Vtx Thread Issue L1 L2 FB 33

Architecture G80 CUDA mode Processors execute computing threads New operating mode/hw interface for computing Host Input Assembler Thread Execution Manager Parallel Data Cache Parallel Data Cache Texture Texture Load/store Parallel Data Cache Texture Load/store Parallel Data Cache Texture Parallel Data Cache Texture Load/store Parallel Data Cache Texture Load/store Global Memory Parallel Data Cache Texture Load/store Parallel Data Cache Texture Texture Load/store 34

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 35

GPU Architecture Pipeline/Architecture of GPU (graphic mode) 36

GPGPU Architecture Each «processor unit» can host a thread Kernel are launch on arrays of thread Each thread runs the same code (SPMD) Each thread has an ID that it uses to compute memory addresses and make control decisions threadid 0 1 2 3 4 5 6 7 float x = input[threadid]; float y = func(x); output[threadid] = y; 37

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 38

GPGPU Architecture How can we distinct a thread from one other? Each Device Grid 1 thread has an Id Can decide what data to work with Each block has also an Id Block (0, 0) Block (1, 0) Block (2, 0) Block (0, 1) Block (1, 1) Block (2, 1) Block (1, 1) Thread Thread Thread Thread Thread (0, 0) (1, 0) (2, 0) (3, 0) (4, 0) Thread Thread Thread Thread Thread (0, 1) (1, 1) (2, 1) (3, 1) (4, 1) Thread Thread Thread Thread Thread (0, 2) (1, 2) (2, 2) (3, 2) (4, 2) 39

GPGPU Architecture Blocks can be 1D or 2D Means Id are 1D or 2D Grid 1 Threads can be 1, 2 or 3D Means Device Id are the same Simplifies memory addressing when processing multidimensional data Image processing Solving PDE on volumes... Block (0, 0) Block (1, 0) Block (2, 0) Block (0, 1) Block (1, 1) Block (2, 1) Block (1, 1) Thread Thread Thread Thread Thread (0, 0) (1, 0) (2, 0) (3, 0) (4, 0) Thread Thread Thread Thread Thread (0, 1) (1, 1) (2, 1) (3, 1) (4, 1) Thread Thread Thread Thread Thread (0, 2) (1, 2) (2, 2) (3, 2) (4, 2) 40

Memory Comparison CPU memory vs. GPU one CPU Memory : At any program point Allocate/free Random local or global memory memory access Registers Local Read/write memory Global Read/write to stack memory Read/write to heap Read/write to disk Disk 41

GPU Memory GPU Memory : restricted acces Allocate/free Limited memory only before computation memory access during computation (kernel) Registers Local memory Read/write Read/write Shared Memory Only available in GPGPU not Graphics pipeline 42

GPU Memory Global memory Virtual Memory Read-only during computation Write-only at end of computation Read/write in GPGPU world only Does not exist! Disk access Does not exist! 43

GPU Memory Where is GPU data stored Vertex buffer Frame buffer Texture Texture Vertex Buffer Vertex Processor Rasterizer Fragment Processor Frame Buffer(s) 44

GPU Memory Vertex buffer Store geometric and radiometric data Framebuffer Store image based data (color, depth, stencil...) Texture Store any kind of information (color, normal, radiometric data...) 45

GPGPU Memory Acces also restricted (Device) Grid Each thread can: Block (0, 0) R/W per-thread registers R/W per-thread local memory Shared 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 Block (1, 0) Host Registers Registers Shared Memory Registers Registers Thread (0, 0) Thread (1, 0) Thread (0, 0) Thread (1, 0) Local Memory Local Memory Local Memory Local Memory Global Memory Constant Memory Texture Memory 46

GPGPU Memory The host can R/W global, constant, and texture memories (Device) Grid Block (0, 0) Block (1, 0) Shared Memory Registers Host Registers Shared Memory Registers Registers Thread (0, 0) Thread (1, 0) Thread (0, 0) Thread (1, 0) Local Memory Local Memory Local Memory Local Memory Global Memory Constant Memory Texture Memory 47

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 memories Constant initialized by host Contents visible to all threads 48

GPGPU Memory Per thread local memory Register Per block memory Shared memory Global memory 49

GPGPU 3. GPGPU on the GPU 50

GPGPU 3. GPGPU on the GPU 3.1 les shaders 51

Cartes graphiques programmable Deux emplacements majeurs programmables 52

Les shaders Deux types de programmes : Les vertex program Les fragment program Intérêt : Adaptabilité De du rendu nouveaux rendus (rapides!) : Autres Matériaux réalistes, Milieux participants, Éclairage par fragment, Ombre, Éclairage réaliste calculs que le rendu Calcul matriciel, Lancer de rayon, Silhouette, Traitement d images, Animation 53

Les shaders Intérêts? 54

Les shaders 55

Les shaders Les vertex program : Informations Sommet Textures VERTEX PROGRAM Variables génériques sommet Information sommet à interpoler dont position, taille des points, clip 56

Les shaders Les fragment program : Informations fragment Textures FRAGMENT PROGRAM Couleur du fragment Profondeur du fragment dont position (image) et front_facing Variables génériques fragment 57

Les shaders Langage particulier pour piloter les programmes Assembleur Dépendent de la carte (ATI / Nvidia) Pénible à écrire à la main Code optimisé Langages haut niveau au dessus de ces assembleurs Appelés shaders les shading languages : langages de 58

Les shaders Historique des langages de shader Shading language : indépendant des cartes graphiques Sorte d'unité programmable atomique Renderman Shading Language (Renderman 88) Adapté au lancer de rayon & rendu photoréaliste Adresse 5 shaders différents : light, displacement, surface, volume et imager ISL : Interactive Shading Language (SGI 00) Encore plus haut niveau. Génère des passes de rendu en OpenGL S adresse directement à des instructions OpenGL 59

Les shaders Historique des langages de shader HLSL Très proche de OpenGLSL : syntaxe, vertex & fragment Adresse DirectX Le shader n est pas compilé par le driver Cg : High-Level Shader Language (Microsoft 02) : 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 60

GPGPU 3. GPGPU on the GPU 3.2 OpenGLSL 61

GLSL : introduction OpenGLSL : un langage de shader libre Proprié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) 62

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éfinies Opérateurs surchargés Pas de pointeur ni de référence Pas de promotion (cast) implicite Passage d argument par valeur 63

GLSL : introduction Architecture : Application Code source shader OpenGL API OpenGL Driver Compilat eur Objet shader Code compilé Link er Objet programme Code exécutable Carte graphique 64

GLSL : introduction Avantages : Colle à OpenGL Compilation à l exécution Indépendant du hardware Compilation par le driver => Meilleures performances Standard 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 65

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 Accès identique : Créé pour des questions de lisibilité vec.r / vec.g / vec.b / vec.a position, couleur, texture vec.s / vec.t / vec.p / vec.q Comme un tableau : vec[0] / vec[1] / vec[2] / vec[3] 66

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. 67

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 68

GLSL : structures Tableaux Déclarés taille];; classiquement : type nom[taille La taille est optionnelle, peut être calculée à la compilation : vec4 vec4 pts[]; pts[]; pts[0] pts[0] == vec4(0,0,0,0); vec4(0,0,0,0); pts[6] pts[6] == vec4(1,0,0,0); vec4(1,0,0,0); // // pts pts est est de de taille taille 77 Redimensionnement explicite ou implicite illégal : vec4 vec4 pts[]; pts[]; vec4 vec4 pts[10]; pts[10]; vec4 vec4 pts[20]; pts[20]; // // Illégal Illégal pts[20] pts[20] == vec4(0,0,0,0); vec4(0,0,0,0); // // Illégal Illégal 69

GLSL : structures Structure Syntaxe Exemple : : struct struct nom_structure nom_structure {{ type type champs champs; }} struct struct kernel3x3 kernel3x3 {{ size size ponderation; ponderation; float float coef[9]; coef[9]; }} Peuvent être emboîtées et encapsulées Peuvent contenir tous les types précédents S utilisent directement sans le mot clé struct kernel3x3 kernel3x3 blur; blur; 70

GLSL : constructeurs «Constructeurs» (initialisation) Scalaire float a,b=3.0,c; a,b=3.0,c; : comme en C : float Autres types : utilisation de constructeur Similaire à un appel de fonction Autant d argument que de valeur à initialiser Exemple : vec4 v = vec4(1.0,2.0,0.0,1.0); kernel3x3 blur = blur(1./9.,{0.0f}); Cas particulier : Constructeur vecteur avec 1 float : remplissage Constructeur matrice avec 1 float : matrice diagonale 71

GLSL : conversions Conversions : vers bool : 0 ou 0.0 => false sinon true de bool : false => 0 / true => 1 Vecteur à Vecteur : La source doit avoir un nombre de composante > destination Affectation dans l ordre. Les termes restants ne sont pas utilisés Vecteur Remplissage dans l ordre de la matrice (colonne major) Matrice à Matrice : à Matrice : Lecture, remplissage en colonne major 72

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 73

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 primitive const : 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) 74

GLSL : flux de données Les vertex program : prédéfinies gl_vertex, gl_normal définies par utilisateur Attribute Uniform VERTEX PROGRAM Textures prédéfinies gl_modelviewmatrix gl_lightsource[0..n] définies par l utilisateur Varying prédéfinies gl_frontcolor gl_fogfragcolor spéciales : gl_position, gl_pointsize gl_clipvertex définies par l utilisateur 75

GLSL : flux de données Fragment program Varying prédéfinies gl_color gl_texcoord[0..n] spéciales : gl_fragcoord gl_frontfacing définies par l utilisateur Uniform Textures FRAGMENT PROGRAM prédéfinies gl_modelviewmatrix gl_lightsource[0..n] définies par l utilisateur Spéciales gl_fragcolor, gl_fragdepth 76

GLSL : flux d'instructions Chaque programme possède un main Quasiment strictement identique au C if else / while / do while / for break / continue Pas de switch, pas de goto Fonctions : identique au C sauf Passage 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 77

GLSL : opérations Similaires à celles du C Arithmétiques Logiques : +, -, *, / : &&,, ^^,!, <, >, <=, >=, Affectation : =, +=, -=, *=, /=, ++, - Sélection :., [],?: ==,!= Opérations sur les vecteurs & matrices Pas 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 78

GLSL : opérations Sélection composantes d un vecteur : swizling Trois groupes de sélection : xyzw, rgba ou stpq On peut les composer / ordonner / restreindre à loisir vec4 v = vec4(1.0,2.0,0.0,3.0); v4.rgba; // vecteur à 4 composantes identique à v4 v4.xy; // vecteur à 2 composantes (1.0,2.0) v4.psq; // vecteur à 3 composantes (0.0,1.0,3.0) v4.g; // C est un float v4.xyba; // Illégal 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.xxzz = v4; // Illégal 79

GPGPU 3. GPGPU on the GPU 3.3 Lien avec l'application 80

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 81

Shader & pipeline Vertex Shader Remplace complètement le pipe line classique Variables 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( ) 82

Shader & pipeline Vertex Shader Variables Utilisation de glvertexattribarb Voir dans la partie suivante Variables uniform prédéfinies Cf. ci-après Variable attribute définies par l utilisateur : uniform définies par l utilisateur Utilisation de gluniformarb Voir dans la partie suivante 83

Shader & pipeline Vertex Shader Variables Variable gl_position Doit impérativement être écrite C est un vec4 Variable gl_pointsize varying spéciales : Taille du point : optionnel C est un float Variable gl_clipvertex Coordonnées du point pour le clipping : optionnel C est un vec4 84

Shader & pipeline Vertex Shader Variables vec4 gl_frontcolor vec4 gl_backcolor vec4 gl_frontsecondarycolor vec4 gl_backsecondarycolor vec4 gl_texcoord[0..n] float gl_fogfragcoord Variables varying prédéfinies : varying définies par l utilisateur Rien à faire coté application. Tout est géré dans le driver 85

Shader & pipeline Fragment Shader Les varying arrivent après interpolation perspective Variables 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 86

Shader & pipeline Fragment Shader Variables uniform : comme pour le vertex shader Variables 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 87

Shader & pipeline Variables uniformes prédéfinies Il 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 : 88

Exemple de shader // VERTEX PROGRAM (tiré (tiré du du Orange Orange Book ) Book ) uniform float float CoolestTemp; CoolestTemp; uniform float float temprange; temprange; // FRAGMENT PROGRAM (tiré attribute float vertextemp; FRAGMENT PROGRAM (tiré du du Orange Orange Book ) Book ) float vertextemp; uniform uniform vec3 CoolestColor; uniform vec3 Temperature; HottestColor; varying uniformfloat float Temperature; varying float void main() { Temperature; varying // // Calcule Calcule le le degre degre de de temperature temperature entre entre 0 et 1 void main() Temperature main() {{= (vertextemp Temperature vertextemp - CoolestTemp CoolestTemp)/ )/temprange temprange; // Utilisation Utilisation d une d une fonction fonction prédéfinie prédéfinie :: mix mix // afin une gl_position gl_modelviewprojectionmatrix afin de de= trouver trouver une couleur couleur mélangée mélangée * gl_vertex;; gl_position } vec3 vec3 color color == mix mix(coolestcolor CoolestColor,,HottestColor HottestColor,,Temperature); gl_fragcolor gl_fragcolor = vec4 vec4(color,1.0); (color,1.0); } 89

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 90

Utilisation des shaders Méthode : 1. 2. 3. 4. 5. Créer un ou plusieurs shaders glcreateshaderobject Leur donner du code source glshadersource Les compiler glcompileshader Créer un objet programme glcreateprogramobject Attacher les shaders à cet objet glattachobject 91

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 8. gluseprogramobject Fournir les variables définies par l utilisateur glgetuniformlocation, gluniform glbindattriblocation, glgetattriblocation, glvertexattrib glenablevertexattribarray, glvertexattribpointer 92

Utilisation des shaders GLhandleARB GLhandleARB loadshaders(const loadshaders(const char char *vertexfile,const *vertexfile,const char char *fragmentfile) *fragmentfile) {{ GLhandleARB GLhandleARB programobject; programobject; // // CREATION CREATION DU DU PROGRAMME PROGRAMME programobject programobject == glcreateprogramobject glcreateprogramobject(); (); if(!programobject) return 0; if(!programobject) return 0; // // CHARGEMENT CHARGEMENT DU DU VERTEX VERTEX SHADER SHADER :: char char *vertexsource; *vertexsource; // // Récupération Récupération de de la la chaine chaine de de caractère caractère du du fichier fichier d entree d entree if (! loadsource (vertexfile, &vertexsource)) return 0; if (!loadsource(vertexfile, &vertexsource)) return 0; // // Creation Creation d'un d'un objet objet qui qui va va contenir contenir des des sources sources GLhandleARB GLhandleARB shaderobject shaderobject == glcreateshaderobject glcreateshaderobject(gl_vertex_shader_arb); (GL_VERTEX_SHADER_ARB); // // Association Association des des sources sources glshadersource glshadersource(shaderobject, (shaderobject, 1, 1, && vertexsource, vertexsource, NULL); NULL); // // Compilation Compilation des des sources sources glcompileshader (shaderobject); glcompileshader(shaderobject); // // Attachement Attachement au au programme programme glattachobject glattachobject(programobject, (programobject, shaderobject); shaderobject); // // Destruction Destruction de de l objet l objet shader shader (inutile (inutile maintenant) maintenant) gldeleteobject gldeleteobject(shaderobject); (shaderobject);...... 93

Utilisation des shaders...... // // CHARGEMENT CHARGEMENT DU DU FRAGMENT FRAGMENT SHADER SHADER :: char char *fragmentsource; *fragmentsource; // Récupération // Récupération de de la la chaine chaine de de caractère caractère du du fichier fichier d entree d entree if if (! (!loadsource loadsource(fragmentfile, (fragmentfile, &fragmentsource)) &fragmentsource)) return return 0; 0; // // Creation Creation d'un d'un objet objet qui qui va va contenir contenir des des sources sources shaderobject shaderobject == glcreateshaderobject glcreateshaderobject(gl_fragment_shader_arb); (GL_FRAGMENT_SHADER_ARB); // // Association Association des des sources sources glshadersource (shaderobject, glshadersource(shaderobject, 1, 1, && fragmentsource, fragmentsource, NULL); NULL); // // Compilation Compilation des des sources sources glcompileshader glcompileshader(shaderobject); (shaderobject); // // Attachement Attachement au au programme programme glattachobject glattachobject(programobject, (programobject, shaderobject); shaderobject); // // Destruction Destruction de de l objet l objet shader shader (inutile (inutile maintenant) maintenant) gldeleteobject (shaderobject); gldeleteobject(shaderobject); // // Linkage Linkage du du programme programme gllinkprogram gllinkprogram(programobject); (programobject); }} // // PLUS PLUS TARD TARD DANS DANS L'INITIALISATION L'INITIALISATION sprog sprog == loadshaders( loadshaders("vert.vert","fragtxt.frag"); "vert.vert","fragtxt.frag"); // // PLUS PLUS TARD TARD DANS DANS LA LA FONCTION FONCTION DE DE DESSIN DESSIN...... gluseprogram gluseprogram(sprog); (sprog); // // si si =0 =0 on on garde garde le le pipeline pipeline classique classique 94

Utilisation des shaders Transmission des variables uniform : Variables Utiliser les instructions classiques OpenGL Variables prédéfinies : 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 95

Utilisation des shaders Variables Récupérer l indice de stockage de la variable : définies par l utilisateur : 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); 96