Programao em GPUs Open GLGLSL CUDA Yalmar Ponce
- Slides: 101
Programação em GPUs (Open. GL/GLSL CUDA) Yalmar Ponce * 13/01/2022
Roteiro § Introdução Tipos de dados, Estruturas, Funções § Shaders § Exemplos Luz (Direcional, Pontual, Spot) Efeitos (Parede de Tijolos, Madeira, Desenho animado) Modificando Geometria § Textura e Multitextura § Shader de Geometria Exemplos § FBO § CUDA § Projeto Final Mapeamento de Sombra (Shadow mapping) 1/13/2022
Introdução § Aplicações Renderização em tempo real Efeitos Jogos 1/13/2022
Introdução § GPUs são rápidas. . . 3. 0 GHz Intel Core Extreme 96 GFLOPS – pico Memory Bandwidth: 13 GB/s Preço: 800~ dólares NVIDIA Ge. Force GTX 280: 930 GFLOPS Memory Bandwidth: 141 GB/s Preço: 499 dólares 1/13/2022
Introdução Graphics State GPU § Versão simplificada da pipeline 1/13/2022 Shade Final Pixels (Color, Depth) Rasterize Fragments (pre-pixels) Assemble Primitives Screenspace triangles (2 D) Transform & Light Xformed, Lit Vertices (2 D) CPU Vertices (3 D) Application Video Memory (Textures) Render-to-texture
Introdução Graphics State Vértices Programável 1/13/2022 Fragment Shade Processor GPU Video Memory (Textures) Render-to-texture § Processador de fragmentos Programável Final Pixels (Color, Depth) § Processador de Rasterize Fragments (pre-pixels) CPU Assemble Primitives Screenspace triangles (2 D) Vertex Transform Processor & Light Xformed, Lit Vertices (2 D) Vertices (3 D) Application
Introdução Graphics State geometria programável 1/13/2022 Fragment Processor GPU Final Pixels (Color, Depth) § Geração de Rasterize Fragments (pre-pixels) CPU Geometry Assemble Processor Primitives Screenspace triangles (2 D) Vertex Processor Xformed, Lit Vertices (2 D) Vertices (3 D) Application Render-to-texture § Acesso a memória mais flexível Video Memory (Textures)
Shaders § Shaders são programas que executam em determinadas etapas do pipeline § Não são aplicações stand-alone § Necessitam de uma aplicação que utilize um API (Open. GL ou Direct 3 D) 1/13/2022
Shaders § No caso: Vertex shader – Vertex Processor Fragment shader – Fragment Processor Geometry shader – Geometry Processor 1/13/2022
Shaders § Vertex Processor Transforma do espaço de mundo para o espaço de tela Calcula iluminação per-vertex 1/13/2022
Shaders § Geometry Processor Como os vértices se conectam para formar a geometria Operações por primitiva 1/13/2022
Shaders § Fragment Processor Calcula a cor de cada pixel Obtém cores de texturas 1/13/2022
Shaders § Hoje a programação de shaders é feita em linguagens de alto nível § No estilo de c/c++ § As principais que temos hoje: GLSL – Open. GL Shader Language HLSL – High Level Shader Language Cg – C for Graphics 1/13/2022
Shaders § Temos algumas ferramentas que servem tanto para criação e edição de shaders: NVIDIA FX Composer 2. 5 Render. Monkey ATI 1/13/2022
Shaders 1/13/2022
Shaders 1/13/2022
Tipos de dados § Estruturas bem intuitivas § Vetores: vec 2, vec 3 e vec 4 – floating point ivec 2, ivec 3 e ivec 4 – interger bvec 2, bvec 3 e bvec 4 – boolean § Matrizes mat 2, mat 3 e mat 4 – floating point 1/13/2022
Tipos de dados § Texturas Sampler 1 D, Sampler 2 D, Sampler 3 D - texturas 1 D, 2 D e 3 D Sampler. Cube – Cube map textures Sampler 1 Dshadow, Sampler 2 DShadow – mapa de profundidade 1 D e 2 D 1/13/2022
Input/Output § Existem 3 tipos de input em um shader: Uniforms Varyings Attributes 1/13/2022
Input/Output § Uniforms Não mudam durante o rendering Ex: Posição da luz ou cor da luz Esta presente em todos os tipos de shader § Varyings Usado para passar dados do vertex shader para o fragment shader ou geometry shader 1/13/2022
Input/Output § Varyings São read-only no fragment e geometry shader mas read/write no vertex shader Deve-se declarar a mesma varying em todos os programas § Attributes Estão presentes apenas nos Vertex shaders São valores (possivelmente diferentes) associados a cada vértice 1/13/2022
Input/Output § Attributes Ex: Posição do vértice ou normais São apenas read-only 1/13/2022
Input/Output § Exemplos de Attributes no vertex shader gl_Vertex – vetor 4 D, posição do vértice gl_Normal – vetor 3 D, Normal do vértice gl_Color – vetor 4 D, cor do vértice gl_Multi. Tex. Coord. X – vetor 4 D, coordenada de textura na unit X Existem vários outros atributos 1/13/2022
Input/Output § Exemplos de Uniforms gl_Model. View. Matrix gl_Model. View. Projection. Matrix gl_Normal. Matrix 1/13/2022
Input/Output § Exemplos de Varyings gl_Front. Color - vetor 4 D com a cor frontal das primitivas gl_Back. Color – vetor 4 D com a cor de trás das primitivas gl_Tex. Coord[N] – vetor 4 D representando a n-ésima coordenada de textura 1/13/2022
Input/Output § Exemplos de output: gl_Position – vetor 4 D representando a posição final do vértice gl_Frag. Color – vetor 4 D representando a cor final que será escrita no frame buffer gl_Frag. Depth – float representando o depth que será escrito do depth buffer 1/13/2022
Input/Output § Também é possível definir attributes, uniforms e varyings § Ex: Passar um vetor tangente 3 D por todos os vértices da sua aplicação § É possível especificar o atributo “tangente” attribute vec 3 tangente; 1/13/2022
Input/Output § Alguns outros exemplos: uniform sampler 2 D my_color_texture; varying vec 3 vertex_to_light_vector; varying vec 3 vertex_to_eye_vector; attribute vec 3 binormal; 1/13/2022
Funções e Estruturas de Controle § Similar a linguagem C § Suporta estruturas de repetição e decisão If/else For Do/while Break Continue 1/13/2022
Funções e Estruturas de Controle § Possui funções como: Seno (sin) Cosseno (cos) Tangente (tan) Potencia (pow) Logaritmo (log 2) Raiz (sqrt) 1/13/2022
GLSL-Setup § Antes de criar os shaders é necessário implementar uma função (no caso do GLSL) para ler e enviar os shaders para o hardware 1/13/2022
GLSL-Setup void set. Shaders(){ char *vs = NULL, *fs 2 = NULL; v = gl. Create. Shader(GL_VERTEX_SHADER); f = gl. Create. Shader(GL_FRAGMENT_SHADER); vs = text. File. Read("minimal. vert"); fs = text. File. Read("minimal. frag"); const char * vv = vs; const char * ff = fs; gl. Shader. Source(v, 1, &vv, NULL); gl. Shader. Source(f, 1, &ff, NULL); free(vs); free(fs); gl. Compile. Shader(v); gl. Compile. Shader(f); p = gl. Create. Program(); gl. Attach. Shader(p, v); gl. Attach. Shader(p, f); gl. Link. Program(p); gl. Use. Program(p); } 1/13/2022
Exemplos simples * 13/01/2022
Hello World § O código shader mais simples Vertex Shader void main() { gl_Position = ftransform(); } Fragment Shader void main(){ gl_Frag. Color = vec 4(0. 4, 0. 8, 1. 0); } 1/13/2022
Modificando a geometria § Achatar o modelo 3 D, ou seja, z=0 void main(void) { vec 4 v = vec 4(gl_Vertex); v. z = 0. 0; gl_Position = gl_Model. View. Projection. Matrix * v; } 1/13/2022
Modificando a geometria II void main(void){ vec 4 v = vec 4(gl_Vertex); v. z = sin(5. 0*v. x )*0. 25; gl_Position = gl_Model. View. Projection. Matrix * v; } 1/13/2022
Animação §É necessário manter a passagem do tempo nos frames § No vertex shader não é possível guardar valores a variável é definida na aplicação Open. GL 1/13/2022
Animação § O shader recebe o valor § A função de render: time numa variável Uniform void render. Scene(void){. . . uniform float time; gl. Uniform 1 f. ARB(loc, time); void main(void){ vec 4 v = vec 4(gl_Vertex); v. z = sin(5. 0*v. x + time*0. 01)*0. 25; gl_Position = gl_Model. View. Projection. Matri x*v; } 1/13/2022 glut. Solid. Teapot(1); time+=0. 01; glut. Swap. Buffers(); }
Manipulação de Texturas § GLSL permite acesso as coordenadas de textura por vértice § GLSL provê variáveis do tipo Attribute, para cada unidade de textura (max 8) attribute vec 4 gl_Multi. Tex. Coord[0. . 8] 1/13/2022
Manipulação de Texturas § Precisa calcular a coordenada de textura § Armazenar numa variável varying gl_Tex. Coord[i] onde i é a unidade de textura utilizada gl_Tex. Coord[0] = gl_Multi. Tex. Coord 0; § Um simples código para definir coordenadas de textura para uma textura utilizando a unit 0 Vertex Shader void main(){ gl_Tex. Coord[0] = gl_Multi. Tex. Coord 0; gl_Position = ftransform(); } 1/13/2022
Manipulação de Texturas § gl_Tex. Coord é uma variável varying § Será utilizada no fragment shader para acessar as coordenadas de textura interpoladas § Para acessar os valores de textura temos que declarar uma variável do tipo uniform no fragment shader § Para uma textura 2 D temos: uniform sampler 2 D tex; 1/13/2022
Manipulação de Texturas § A função que nos retorna um textel é a texture 2 D § Os valores retornados levam em consideração todos as definições de textura feitos no Open. GL (filtering, mipmap, clamp, etc) 1/13/2022
Manipulação de Texturas § Vertex Shader void main(){ gl_Tex. Coord[0] = gl_Multi. Tex. Coord 0; gl_Position = ftransform(); } § Fragment shader uniform sampler 2 D tex; void main() { vec 4 color = texture 2 D(tex, gl_Tex. Coord[0]. st); gl_Frag. Color = color; } 1/13/2022
Múltiplas Texturas § Definir as texturas gl. Gen. Textures(1, &Textura); gl. Bind. Texture(GL_TEXTURE_2 D, Textura); gl. Tex. Parameteri(GL_TEXTURE_2 D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); gl. Tex. Parameteri(GL_TEXTURE_2 D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); gl. Tex. Image 2 D(GL_TEXTURE_2 D, level, format, GL_RGB, GL_UNSIGNED_BYTE, Texure. Info); Width, Height, § Na aplicação Open. GL, é necessário habilitar as texturas que serão usadas. gl. Activate. Texture(GL_TEXTUREi) onde i = 0. . 8 1/13/2022 0,
Múltiplas Texturas § Multi Texturing gl. Enable (GL_TEXTURE_2 D); gl. Active. Texture(GL_TEXTURE 0); gl. Bind. Texture(GL_TEXTURE_2 D, texid 0); gl. Active. Texture(GL_TEXTURE 1); gl. Bind. Texture(GL_TEXTURE_2 D, texid 1); . . . gl. Begin(GLenum Mode); . . . gl. End(); gl. Disable (GL_TEXTURE_2 D); 1/13/2022
GLSL e Multi-Textura § Cada textura que será usada no programa GLSL deve ser associada a uma textura na aplicação Open. GL. Vertex/Fragment Shader uniform sampler 2 D texture. Name 1, texture. Name 2; Programa Open. GL (inicialiazação) GLuint tex 1, tex 2; GLint tex. Loc 1, tex. Loc 2; tex. Loc 1 = gl. Get. Uniform. Location(program. Obj, "texture. Name 1"); tex. Loc 2 = gl. Get. Uniform. Location(program. Obj, "texture. Name 2"); gl. Uniform 1 i(tex. Loc 1, 0); // a primeira deve ser 0 gl. Uniform 1 i(tex. Loc 2, 1); Programa Open. GL ( ativar multitextura) gl. Enable(GL_TEXTURE_2 D); gl. Active. Texture(GL_TEXTURE 0); // habilita para uso tex 1 gl. Active. Texture(GL_TEXTURE 1); // habilita para uso tex 2 draw. Quad(); Note que a textura atribuída com a função gl. Uniform 1 i(tex. Loc 1, i) i = 0, 1, . . . gl. Active. Texture(GL_TEXTUREi) antes 1/13/2022 deve ser ativada com de usar um programa GLSL
Textura 3 D gl. Gen. Textures(1, &Tex. Name); gl. Bind. Texture(GL_TEXTURE_3 D, Tex. Name); gl. Tex. Parameterf(GL_TEXTURE_3 D, GL_TEXTURE_WRAP_S, GL_REPEAT); gl. Tex. Parameterf(GL_TEXTURE_3 D, GL_TEXTURE_WRAP_T, GL_REPEAT); gl. Tex. Parameterf(GL_TEXTURE_3 D, GL_TEXTURE_WRAP_R, GL_REPEAT); gl. Tex. Parameterf(GL_TEXTURE_3 D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); gl. Tex. Parameterf(GL_TEXTURE_3 D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); gl. Tex. Image 3 D(GL_TEXTURE_3 D, 0, GL_RGBA, Tex. Size, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); 1/13/2022
Exemplos mais complexos * 13/01/2022
Efeito tijolo § Vertex Shader http: //www. 3 dshaders. com/shaders § 2 nd. Ed/CH 06 -brick. vert. txt Fragment Shader http: //www. 3 dshaders. com/shaders 2 nd. Ed/CH 06 -brick. frag. txt 1/13/2022
Effeito madeira § Vertex Shader http: //www. 3 dshaders. com/ shaders 2 nd. Ed/CH 15 wood. vert. txt § Fragment Shader http: //www. 3 dshaders. com/ shaders 2 nd. Ed/CH 15 wood. frag. txt 1/13/2022
Efeito nuvem § § Vertex Shader http: //www. 3 dshaders. com/sha ders 2 nd. Ed/CH 15 -cloud. vert. txt Fragment Shader http: //www. 3 dshaders. com/sha ders 2 nd. Ed/CH 15 -cloud. frag. txt 1/13/2022
Geometry Shader * 13/01/2022
Geometry Shader § Permite mudar a geometria de entrada § Necessário especificar a geometria de entrada e saida gl. Program. Parameteri. EXT(GLhandle. ARB program, GL_GEOMETRY_INPUT_TYPE_EXT, GL_LINES_ADJACENCY_EXT); gl. Program. Parameteri. EXT(GLhandle. ARB program, GL_GEOMETRY_OUTPUT_TYPE_EXT, GL_TRIANGLE_STRIP); § Adicionalmente deve ser especificado o número máximo de vértices a serem criados gl. Get. Integerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT, &temp); gl. Program. Parameteri. EXT(GLhandle. ARB program, GL_GEOMETRY_VERTICES_OUT_EXT, temp); 1/13/2022
Geometry Shader § § § Convenções #version 120 #extension GL_EXT_geometry_shader 4 : enable Geometry language built-in outputs: varying out vec 4 gl_Front. Color; varying out vec 4 gl_Back. Color; varying out vec 4 gl_Front. Secondary. Color; varying out vec 4 gl_Back. Secondary. Color; varying out vec 4 gl_Tex. Coord[]; // at most gl_Max. Texture. Coords varying out float gl_Fog. Frag. Coord; Geometry language input varying variables: varying in vec 4 gl_Front. Color. In[gl_Vertices. In]; varying in vec 4 gl_Back. Color. In[gl_Vertices. In]; varying in vec 4 gl_Front. Secondary. Color. In[gl_Vertices. In]; varying in vec 4 gl_Back. Secondary. Color. In[gl_Vertices. In]; varying in vec 4 gl_Tex. Coord. In[gl_Vertices. In][]; varying in float gl_Fog. Frag. Coord. In[gl_Vertices. In]; varying in vec 4 gl_Position. In[gl_Vertices. In]; varying in float gl_Point. Size. In[gl_Vertices. In]; varying in vec 4 gl_Clip. Vertex. In[gl_Vertices. In]; 1/13/2022
Exemplo #version 120 #extension GL_EXT_geometry_shader 4: enable #extension GL_EXT_gpu_shader 4: enable varying out out vec 3 . . . eye. Normal = n 0; v. Normal = vn 0; eye. Position = py 0; gl_Position = pt 0; Emit. Vertex(); v. Normal = vn 1; eye. Position = py 1; gl_Position = pt 1; Emit. Vertex(); v. Normal = vn 2; eye. Position = py 2; gl_Position = pt 2; Emit. Vertex(); eye. Normal; v. Normal; eye. Position; Light. Position; void main(void){ vec 4 v = gl_Position. In[0]; Light. Position = gl_Light. Source[0]. position; vec 4 p 0 = texture 2 D(vtx_tex, get. Pos(v. x)); vec 4 p 1 = texture 2 D(vtx_tex, get. Pos(v. y)); vec 4 p 2 = texture 2 D(vtx_tex, get. Pos(v. z)); vec 4 p 3 = texture 2 D(vtx_tex, get. Pos(v. w)); . . . End. Primitive(); } 1/13/2022
Exemplo #version 120 #extension EXT_gpu_shader 4 : require varying vec 3 eye. Normal; v. Normal; eye. Position; Light. Position; void main() { vec 3 light = normalize( Light. Position ); vec 3 r = reflect( eye. Position, eye. Normal)*0. 5; vec 3 red = vec 3( 0. 23, 0. 52, 0. 72); const vec 3 white = vec 3( 1, 1, 1); float ndotl = max(dot( eye. Normal, light), 0. 0); if (ndotl == 0. 0) ndotl = dot( eye. Normal, -light); ndotl = min( max( ndotl, 0. 0) + 0. 2, 1. 0); float spec = pow( max( 0. 0, dot( r, light)), 32. 0); vec 3 color = clamp( ndotl*red + spec*white, 0. 0, 1. 0); gl_Frag. Color = vec 4( color, 1. 0); } 1/13/2022
Conclusões § Diversos tipos de aplicações 1/13/2022
Conclusões 1/13/2022
Classe C++ para o Setup GLSL § LCG Toolkit http: //code. google. com/u/andmax/ 1/13/2022
Exemplo de uso #include "glslkernel. h“ GLSLKernel VBOShader; VBOShader. vertex_source("vertex. glsl"); VBOShader. geometry_source("geometry. glsl"); VBOShader. fragment_source("fragment. glsl"); VBOShader. set_geom_max_output_vertices(12); VBOShader. set_geom_input_type(GL_POINTS); VBOShader. set_geom_output_type(GL_TRIANGLE_STRIP); VBOShader. install(true); VBOShader. use(true); VBOShader. set_uniform("vtx_tex", 0); VBOShader. use(true); gl. Draw. Elements( GL_POINTS, n_points, GL_UNSIGNED_INT, 0); VBOShader. use(false); 1/13/2022
Framebuffers * 13/01/2022
Frame buffer § Escrita em memória é feito pelo processador de § fragmentos Memória GPU apenas de escrita VS 3. 0 GPUs Texture Vertex Buffer 1/13/2022 Vertex Processor Rasterizer Fragment Processor Frame Buffer(s)
Open. GL Framebuffer Objects § Ideia Geral Framebuffer object pode ser visto como uma estrutura de ponteiros Associar memória da GPU a um framebuffer como writeonly A memória não pode ser lida enquanto estiver associada ao framebuffer § Qual memória? Texture (RGBA) Renderbuffer Framebuffer Object Vertex buffer? ? 1/13/2022 Renderbuffer (Depth) 63
Framebuffer Objects § O que é um FBO? Uma estrutura que manipula ponteiros e objetos memória Cada objeto memória associado pode ser usado como um framebuffer para rendering 1/13/2022 64
Framebuffer Objects (FBOs) § Open. GL extension Habilita render-to-texture in Open. GL Mix-and-match depth/stencil buffers Substitui pbuffers! Platform-independent http: //oss. sgi. com/projects/ogl-sample/registry/EXT/framebuffer_object. txt 1/13/2022 65
Framebuffer Objects § Quais tipos de memória podem ser associados a um FBO? Textures Renderbuffers Depth, stencil, color Framebuffers de escrita tradicionais 1/13/2022 66
Que é um Renderbuffer? § Modelo “Traditional” de memória framebuffer Memória GPU Write-only Color buffer Depth buffer Stencil buffer § Novo objeto de memória Open. GL Parte do Framebuffer Object extension 1/13/2022 67
Renderbuffer § Operações suportadas CPU interface Allocate Free Copia GPU CPU Associar para acesos write-only no framebuffer 1/13/2022 68
Framebuffer Objects § Modo de uso Pode ter N texturas associadas a um FBO (até 16) destinos de rendering são cambiados com gl. Draw. Buffers Manter uma FBO para cada tamanho/formato Mudar destinos de rendering attach/unattach textures Pode ter diferentes FBOs com texturas vinculadas Mudar destinos de rendering ligando (bind) FBOs 1/13/2022 69
Framebuffer Objects § Performance Render-to-texture gl. Draw. Buffers Mais eficientes que pbuffers Attach/unattach texturas é mais eficiente que mudar de FBO Manter formato/tamanho idêntico para todas as memórias associadas ao FBO Readback gl. Read. Pixels 1/13/2022 70
Framebuffer Object § Exemplos e maiores detalhes Classes C++ de FBO e Renderbuffer http: //gpgpu. sourceforge. net/ Open. GL Spec http: //oss. sgi. com/projects/ogl-sample/registry/EXT/framebuffer_object. txt 1/13/2022 71
Pixel Buffer Objects § Mecanismo eficiente para transferir pixel data API parecido com vertex buffer objects VS 3. 0 GPUs Texture Vertex Buffer 1/13/2022 Vertex Processor Rasterizer Fragment Processor Frame Buffer(s) 72
Pixel Buffer Objects § Usos Render-to-vertex-array gl. Read. Pixels no GPU-based pixel buffer Usar pixel buffer como vertex buffer Streaming de textures rápido Mapear PBO na memória da CPU Escrever diretamente ao PBO Reduz uma ou mais cópias Readback asincrono Cópia de dados GPU CPU não-bloqueante gl. Read. Pixels no PBO não bloqueiado É bloqueiado quando PBO é mapeiado na memória da CPU 1/13/2022 73
Resumo : Render-to-Texture § Operação básica em apps GPGPU § Suporte Open. GL Valores de 16, 32 -bit por pixel Render-to-texture 1/13/2022 Multiple Render Targets (MRTs) e Copy-to-texture gl. Copy. Tex. Sub. Image GL_EXT_framebuffer_object
Resumo : Render-To-Vertex-Array § Habilita retro-alimentação § Suporte Open. GL Copy-to-vertex-array GL_ARB_pixel_buffer_object NVIDIA e ATI Render-to-vertex-array Não disponível 1/13/2022 75
Estruturas de dados básicas na GPU § “Implementing Efficient Parallel Data Structures on GPUs” Chapter 33, GPU Gems II § Low-level details 1/13/2022 76
GPU Arrays § Large 1 D Arrays Limite das GPUs em array 1 D até 2048 ou 4096 Empacotados em memória 2 D Precisa de mapear o endereço 1 D-to-2 D 1/13/2022 77
GPU Arrays § 3 D Arrays Problem GPUs não possuem 3 D frame buffers Soluções 1. Empilhar fatias 2 D 2. Múltiplas fatias de buffers 2 D 3. Render-to-slice-of-3 D-texture (NVidia G 8) 1/13/2022 78
Exemplo: Simulação de Tecido § § § Integration de Verlet Jakobsen, GDC 2001 Evita guardar velocidade explicita new_x = x + (x – old_x)*damping + a*dt*dt Não é exato, mas sim estável! Precisa guardar a posição atual é a anterior para cada partícula 2 RGB float textures O Fragment shader calcula a nova posição e escreve o resultado em outra textura (float buffer) Logo, intercambia as texturas atual e anterior 1/13/2022
Algoritmo § Requer de 4 passos § A cada passo renderiza uma quad com o fragment shader: 1. Executa a integração (move as partículas) 2. Aplica restrições (constraints): Restrição de distância entre partículas Colisão com os obstáculos (piso, esfera) 3. Calcula as normais 4. Renderiza a malha do tecido usando VBO 1/13/2022
Código da Integração uniform sampler 2 DRect oldp_tex; uniform sampler 2 DRect currp_tex; // Verlet integration step void Integrate(inout vec 3 x, inout vec 3 oldx, vec 3 a, float timestep 2){ vec 3 tmpx = x; x = 2*x - oldx + a*timestep 2; oldx = tmpx; } void main() { float timestep = 0. 02; vec 3 gravity = vec 3(0. 0, -9. 8, 0. 0); vec 2 uv = gl_Tex. Coord[0]. st; // get current and previous position vec 3 oldx = texture 2 DRect(oldp_tex, uv). rgb; vec 3 x = texture 2 DRect(currp_tex, uv). rgb; // move the particle Integrate(x, oldx, gravity, timestep*timestep); gl_Frag. Color = vec 4(x, 1. 0); } 1/13/2022
Código das restrições void main(){ const float stiffness = 0. 2; vec 2 uv = gl_Tex. Coord[0]. st; // this should really be 0. 5 vec 3 x = texture 2 DRect(x_tex, uv). rgb; // get current position x = clamp(x, world. Min, world. Max); // satisfy world constraints Sphere. Constraint(x, sphere. Pos, 1. 0); // collision constraint with the sphere // get positions of neighbouring particles vec 3 x 1 = texture 2 DRect(x_tex, uv + vec 2(1. 0, 0. 0)). rgb; vec 3 x 2 = texture 2 DRect(x_tex, uv + vec 2(-1. 0, 0. 0)). rgb; vec 3 x 3 = texture 2 DRect(x_tex, uv + vec 2(0. 0, 1. 0)). rgb; vec 3 x 4 = texture 2 DRect(x_tex, uv + vec 2(0. 0, -1. 0)). rgb; vec 3 x 5 = texture 2 DRect(x_tex, uv + vec 2(-1. 0, -1. 0)). rgb; vec 3 x 6 = texture 2 DRect(x_tex, uv + vec 2(1. 0, 1. 0)). rgb; // apply distance constraints vec 3 dx = vec 3(0. 0); if (uv. x < mesh. Size. x) dx = Distance. Constraint(x, x 1, dist, stiffness); if (uv. x > 0. 5) dx = dx + Distance. Constraint(x, x 2, dist, stiffness); if (uv. y < mesh. Size. y) dx = dx + Distance. Constraint(x, x 3, dist, stiffness); if (uv. y > 0. 5) dx = dx + Distance. Constraint(x, x 4, dist, stiffness); if (uv. x > 0. 5 && uv. y > 0. 5) dx = dx + Distance. Constraint(x, x 5, dist 2, stiffness); if (uv. x < mesh. Size. x && uv. y < mesh. Size. y) dx = dx + Distance. Constraint(x, x 6, dist 2, stiffness); x = x + dx; gl_Frag. Color = vec 4(x, 1. 0); } 1/13/2022
Resultado 1/13/2022
Objetos deformáveis § A abordagem massa-mola usada na simulação de tecido pode ser estendida para simular objetos deformáveis. O objeto é representado por uma malha tetraédrica (sem slivers) Define-se uma restrição de distância (constraint) para cada aresta da malha. Cada vértice requer a lista de arestas incidentes (processo de relaxamento) 1/13/2022
Objetos deformáveis 1/13/2022
Introdução à API CUDA * 13/01/2022
Ge. Force 6 Architecture
Ge. Force 8800 GPU § § Unidades programáveis Shader unificado
GPU Architecture
CUDA–C Sem limitações dos shaders! § Aplicações integradas host + device C program Partes serial e paralelo no código C host Partes totalmente em paralelo no código C device kernel C Código Serial (host) Kernel Paralelo (device) Kernel. A<<< n. Blk, n. Tid >>>(args); . . . Código Serial (host) Kernel Paralelo (device) Kernel. B<<< n. Blk, n. Tid >>>(args); . . .
IDs de Blocos e IDs de Threads § Cada thread usa IDs para decidir os dados com os que deve trabalhar Block ID: 1 D ou 2 D Thread ID: 1 D, 2 D, ou 3 D § Memoria simplificada Endereçamento Dados multidimensionais
Visão geral do Modelo de Memória do CUDA § § Memória Global Permite a comunicação de dados R/W entre host e device Visível a todos os threads Grid Access não é rápido Memória Constante Block (0, 0) Memória compartilhada Registradores locais Shared Memory Registers Thread (0, 0) Thread (1, 0) Host Global Memory Block (1, 0) Shared Memory Registers Thread (0, 0) Thread (1, 0)
CUDA Exemplo: Multiplicação de matrizes – Versão Host simples em C M k WIDTH void Matrix. Mul. On. Host(float* M, float* N, float* P, int Width){ for (int i = 0; i < Width; ++i) N for (int j = 0; j < Width; ++j) { double sum = 0; for (int k = 0; k < Width; ++k) { double a = M[i * width + k]; j double b = N[k * width + j]; sum += a * b; } P[i * Width + j] = sum; } } P WIDTH i k WIDTH
CUDA Exemplo: Multiplicação de matrizes – Versão GPU void Matrix. Mul. On. Device(float* M, float* N, float* P, int Width){ int size = Width * sizeof(float); float* Md, Nd, Pd; // Allocate and Load M, N to device memory cuda. Malloc(&Md, size); cuda. Memcpy(Md, M, size, cuda. Memcpy. Host. To. Device); cuda. Malloc(&Nd, size); cuda. Memcpy(Nd, N, size, cuda. Memcpy. Host. To. Device); // Allocate P on the device cuda. Malloc(&Pd, size); dim 3 dim. Grid(1, 1); dim 3 dim. Block(Width, Width); // Launch the device computation threads! Matrix. Mul. Kernel<<<dim. Grid, dim. Block>>>(Md, Nd, Pd, Width); cuda. Memcpy(P, Pd, size, cuda. Memcpy. Device. To. Host); // Read P from device cuda. Free(Md); cuda. Free(Nd); cuda. Free (Pd); }
CUDA Exemplo: Multiplicação de matrizes – Versão GPU void Matrix. Mul. On. Device(float* M, float* N, float* P, int Width) { int size = Width * sizeof(float); Allocate float* Md, Nd, Pd; // Allocate and Load M, N to device memory on cuda. Malloc(&Md, size); cuda. Memcpy(Md, M, size, cuda. Memcpy. Host. To. Device); cuda. Malloc(&Nd, size); cuda. Memcpy(Nd, N, size, cuda. Memcpy. Host. To. Device); // Allocate P on the device cuda. Malloc(&Pd, size); device dim 3 dim. Grid(1, 1); dim 3 dim. Block(Width, Width); // Launch the device computation threads! Matrix. Mul. Kernel<<<dim. Grid, dim. Block>>>(Md, Nd, Pd, Width); cuda. Memcpy(P, Pd, size, cuda. Memcpy. Device. To. Host); // Read P from device cuda. Free(Md); cuda. Free(Nd); cuda. Free (Pd); }
CUDA Exemplo: Multiplicação de matrizes – Versão GPU void Matrix. Mul. On. Device(float* M, float* N, float* P, int Width) { int size = Width * sizeof(float); float* Md, Nd, Pd; // Allocate and Load M, N to device memory cuda. Malloc(&Md, size); cuda. Memcpy(Md, M, size, cuda. Memcpy. Host. To. Device); cuda. Malloc(&Nd, size); cuda. Memcpy(Nd, N, size, cuda. Memcpy. Host. To. Device); // Allocate P on the device cuda. Malloc(&Pd, size); Do Matrix multiplication on device dim 3 dim. Grid(1, 1); dim 3 dim. Block(Width, Width); // Launch the device computation threads! Matrix. Mul. Kernel<<<dim. Grid, dim. Block>>>(Md, Nd, Pd, Width); cuda. Memcpy(P, Pd, size, cuda. Memcpy. Device. To. Host); // Read P from device cuda. Free(Md); cuda. Free(Nd); cuda. Free (Pd); }
CUDA Exemplo: Multiplicação de matrizes – Versão GPU void Matrix. Mul. On. Device(float* M, float* N, float* P, int Width) { int size = Width * sizeof(float); float* Md, Nd, Pd; // Allocate and Load M, N to device memory cuda. Malloc(&Md, size); cuda. Memcpy(Md, M, size, cuda. Memcpy. Host. To. Device); cuda. Malloc(&Nd, size); cuda. Memcpy(Nd, N, size, cuda. Memcpy. Host. To. Device); // Allocate P on the device cuda. Malloc(&Pd, size); Free device memory dim 3 dim. Grid(1, 1); dim 3 dim. Block(Width, Width); // Launch the device computation threads! Matrix. Mul. Kernel<<<dim. Grid, dim. Block>>>(Md, Nd, Pd, Width); cuda. Memcpy(P, Pd, size, cuda. Memcpy. Device. To. Host); // Read P from device cuda. Free(Md); cuda. Free(Nd); cuda. Free (Pd); }
CUDA Exemplo: Multiplicação de matrizes – Versão GPU for (int k = 0; k < Width; ++k) { float Melement = Md[thread. Idx. y*Width+k]; float Nelement = Nd[k*Width+thread. Idx. x]; Pval += Melement * Nelement; } Pd[thread. Idx. y*Width+thread. Idx. x] = Pval; k WIDTH // Matrix multiplication kernel – per thread code __global__ void Matrix. Mul. Kernel(float* Md, float* Nd, float* Pd, int Width) { Nd // Pvalue is used to store the element of the matrix // that is computed by the thread float Pval = 0; tx } Md Pd ty WIDTH ty tx k WIDTH
Exemplos
Referências § http: //www. mathematik. uni- dortmund. de/~goeddeke/gpgpu § http: //www. gpgpu. org § http: //developer. nvidia. com/object/sdk_home § http: //www. nvidia. com/object/cuda_home. html 1/13/2022
- Analyzing and leveraging decoupled l1 caches in gpus
- Gpu sql databases
- Understanding the efficiency of ray traversal on gpus
- Sah bvh
- 영국 beis
- Scarlitte
- Ponce de leon the fountain of youth
- Ponce de leon motives for exploration
- Juan ponce de leon
- John cabot motives
- Ponce de leon the fountain of youth
- Manejo de emergencias ponce
- Sebastien ponce
- Henry hudson birth and death
- Mapa de desalojo por tsunami ponce
- Juan ponce de leon fountain of youth
- Ponce de leon nationality
- Ponce de len
- Briana ponce
- Trubner's record of rizal
- Rodolfo ponce vargas
- Years of exploration juan ponce de leon
- Cuda
- Cuda
- Cuda
- Cuda atomic
- Oit.duke.edu
- Sparse matrix multiplication cuda
- What is texture memory
- Cuda threads per block
- Cuda platform
- Opis na likot alisa
- Pixels cda
- Cuda
- "spherical communications"
- What is parallel reduction?
- John cuda
- Exclusive scan cuda
- Cuda jpeg encoder
- Cuda opencl
- Cuda
- What is cuda
- Nvidia t239
- Vmware workstation cuda
- Cuda shared memory size
- Cuda memory model
- Cuda synchronize threads
- Cuda
- Hwschedules
- Cuda get device properties
- Cuda overview
- Matrix multiplication cuda
- Cuda event elapsed time
- Cuda svd
- Cuda
- Cuda
- Cuda
- Conclusion of parallel computing
- Cuda architecture explanation
- Cuda divergence
- Cuda divergence
- Cuda programming model
- Cuda
- 8 svetskih cuda
- Cuda
- Mergesort cuda
- Thrust cuda
- Cuda math library
- Syncthreads
- Opis na likot alisa
- Pycuda tutorial
- Cuda texture object example
- Cuda
- Cuda
- Stilska figura obracanja
- Cuda matrix multiplication optimization
- Cuda programming model
- Cuda in r
- Cuda stream priority
- Hpcg benchmark
- Nvidia cuda comparison
- "normally open, timed-closed contact symbol"
- Open hearts open hands
- Is zotero open source
- Open disclosure definition
- Jefferson lab
- Open unified process (openup)
- Open aire
- The cask of amontillado questions
- Digital cemetary
- Software dentisti open source
- Qnl open access
- Open your book
- Axial coding
- "open range" -ranch -trailer
- Ardustat
- Open door policy aim
- Managed open source
- Unionville high school principal
- Microsoft.open.azuread.model.passwordprofile
- Open box problem
- Open circulatory system vs closed