GPU Programming

Direct X
Setup vertex buffer: struct MY_V3F { FLOAT x, y, z;   FLOAT u, v; };

static const MY_V3F triangleVertices[] = { // X      Y     Z     U     V    { -1.0f, -1.0f, 0.0f, 0.0f, 0.0f }, { -1.0f, 1.0f, 0.0f, 0.0f, 1.0f }, { 1.0f,  1.0f, 0.0f, 1.0f, 1.0f }, { 1.0f, -1.0f, 0.0f, 1.0f, 0.0f } };

static LPDIRECT3DVERTEXBUFFER9 myVertexBuffer = NULL; static LPDIRECT3DINDEXBUFFER9 index_buffer = NULL;

if (FAILED(pDev->CreateVertexBuffer(		sizeof(triangleVertices),		0,		D3DFVF_XYZ | D3DFVF_TEX2,		D3DPOOL_DEFAULT,		&myVertexBuffer,		NULL))) return E_FAIL;

void* pVertices; if (FAILED(myVertexBuffer->Lock(		0,		0, /* map entire buffer */		&pVertices,		0))) return E_FAIL;

memcpy(pVertices, triangleVertices, sizeof(triangleVertices)); myVertexBuffer->Unlock;

static const unsigned int indices[] = { 0, 1, 2, 0, 2, 3};

if(FAILED(pDev->CreateIndexBuffer(		sizeof(indices) / sizeof(unsigned int), // length		0,                                     // usage flags		D3DFMT_INDEX32,                         // format		D3DPOOL_DEFAULT,                        // memory pool		& index_buffer,		NULL))) return E_FAIL;

void * index_buffer_ptr; if(FAILED(index_buffer->Lock(0, 0, & index_buffer_ptr, 0))) return E_FAIL; memcpy(index_buffer_ptr, indices, sizeof(indices)); index_buffer->Unlock; Render geometry: pDev->SetStreamSource(0, myVertexBuffer, 0, sizeof(MY_V3F)); pDev->SetIndices( index_buffer ); pDev->SetFVF(D3DFVF_XYZ|D3DFVF_TEX2);

pDev->DrawIndexedPrimitive(		D3DPT_TRIANGLELIST, // type		0,                 // index offset		0,                  // minimum index		6,                  // # of vertices		0,                  // start index		2                   // primitive count		); Cleanup: static void CALLBACK OnLostDevice(void* userContext) { myVertexBuffer->Release; index_buffer->Release; cgD3D9SetDevice(NULL); }

Setting Values in Shaders
Let's say we have a fragment shader with a time parameter: struct Fragment_out { float4 color : COLOR; }; Fragment_out my_fragment(uniform float time) { Fragment_out out; float v = sin(time) * 0.5 + 0.5; out.color = float4(v,v,v,1); } We want to set the time parameter from the application.

Direct X

 * 1) include 
 * 2) include 
 * 3) include "DXUT.h"

CGparameter shader_time; static CGprogram myCgFragmentProgram; static void createCgPrograms { ...   myCgFragmentProgram = cgCreateProgramFromFile( ... ); shader_time = cgGetNamedParameter(myCgFragmentProgram, "time"); ... } static void CALLBACK OnFrameRender(IDirect3DDevice9* pDev,	double time,	float elapsedTime, void* userContext) { if (SUCCEEDED(pDev->BeginScene)) { ...	cgD3D9BindProgram(myCgFragmentProgram); float t = time; cgD3D9SetUniform(shader_time, & t ); ...	pDev->EndScene; } }