Upload
meredith-pugh
View
20
Download
2
Embed Size (px)
DESCRIPTION
DIRECT3D. Visão geral. Parte da API DirectX da Microsoft [1] Disponível a partir do Windows 95 Utilizado para renderizar gráficos tridimensionais Permite que as aplicações rodem em tela cheia e em janela Utiliza aceleração de hardware se disponível no chip gráfico. [2]. Características. - PowerPoint PPT Presentation
Citation preview
Visão geral
Parte da API DirectX da Microsoft [1] Disponível a partir do Windows 95 Utilizado para renderizar gráficos
tridimensionais Permite que as aplicações rodem em
tela cheia e em janela Utiliza aceleração de hardware se
disponível no chip gráfico
Características
Z-buffering Anti-aliasing Composição alfa MipMaping Efeitos de atmosfera Mapeamento de textura em perspectiva
COM Component Object Model Método para criação de objetos
avançados Atua como objetos montáveis (“Lego”)
Classes C++ ou grupos de classes nos quais pode-se chamar funções para atingir certos objetivos
Classes não necessitam das outras para operar Pode-se plugar e desplugar
Por que COM?
DirectX é uma série de objetos COM, sendo um dos quais o Direct3D
Classe avançada que contém todo o necessário para rodar gráficos 2D e 3D
Ex: d3d->CreateDevice() d3d->Release() Interface Direct3D
Primeiro programa Direct3D Direct3D não é uma linguagem em si Primeiro programa: preencher uma
janela de azul Criar variáveis globais e protótipos de
funções Criar função que inicializa Direct3D e
cria dispositivo Direct3D Criar função para renderizar um frame Criar função para fechar Direct3D
1 // include the basic windows header files and the Direct3D header file
#include <windows.h>#include <windowsx.h>#include <d3d9.h>
// include the Direct3D Library file#pragma comment (lib, "d3d9.lib")
// global declarationsLPDIRECT3D9 d3d; // the pointer to our Direct3D interfaceLPDIRECT3DDEVICE9 d3ddev; // the pointer to the device class
// function prototypesvoid initD3D(HWND hWnd); // sets up and initializes Direct3Dvoid render_frame(void); // renders a single framevoid cleanD3D(void); // closes Direct3D and releases memory
// the WindowProc function prototypeLRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
2 // this function initializes and prepares Direct3D for use
void initD3D(HWND hWnd){ d3d = Direct3DCreate9(D3D_SDK_VERSION); // create the Direct3D interface
D3DPRESENT_PARAMETERS d3dpp; // create a struct to hold various device information
ZeroMemory(&d3dpp, sizeof(d3dpp)); // clear out the struct for use d3dpp.Windowed = TRUE; // program windowed, not fullscreen d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; // discard old frames d3dpp.hDeviceWindow = hWnd; // set the window to be used by Direct3D
// create a device class using this information and information from the d3dpp stuct d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &d3ddev);}
3 // this is the function used to render a single frame
void render_frame(void){ // clear the window to a deep blue d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 40, 100), 1.0f, 0);
d3ddev->BeginScene(); // begins the 3D scene
// do 3D rendering on the back buffer here
d3ddev->EndScene(); // ends the 3D scene
d3ddev->Present(NULL, NULL, NULL, NULL); // displays the created frame}
4
// this is the function that cleans up Direct3D and COMvoid cleanD3D(void){ d3ddev->Release(); // close and release the 3D device d3d->Release(); // close and release Direct3D}
Tela cheia
É necessário mudar alguns detalhes no código
Muitas vezes é importante saber o tamanho da tela
Problemas Mudar resolução em tempo de execução
2 hWnd = CreateWindowEx(NULL,
L"WindowClass", L"Our Direct3D Program", WS_OVERLAPPEDWINDOW, 300, 300, SCREEN_WIDTH, SCREEN_HEIGHT, // set window to new resolution NULL, NULL, hInstance, NULL);
Mudando para tela cheia hWnd = CreateWindowEx(NULL,
L"WindowClass", L"Our Direct3D Program", WS_EX_TOPMOST | WS_POPUP, // fullscreen values 0, 0, // the starting x and y positions should be 0 SCREEN_WIDTH, SCREEN_HEIGHT, NULL, NULL, hInstance, NULL);
Nova resolução D3DPRESENT_PARAMETERS d3dpp; // create a struct to
hold various device information
ZeroMemory(&d3dpp, sizeof(d3dpp)); // clear out the struct for use d3dpp.Windowed = FALSE; // program fullscreen, not windowed d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; // discard old frames d3dpp.hDeviceWindow = hWnd; // set the window to be used by Direct3D d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8; // set the back buffer format to 32-bit d3dpp.BackBufferWidth = SCREEN_WIDTH; // set the width of the buffer d3dpp.BackBufferHeight = SCREEN_HEIGHT; // set the height of the buffer
Estrutura
Criamos uma estrutura com essas flags. Usamos ela ao invés de chamar todo o código FVF toda vez.
#define CUSTOMFVF (D3DFVF_XYZRHW | D3DFVF_DIFFUSE)
Estrutura do Vértice
struct CUSTOMVERTEX{ FLOAT x, y, z, rhw; // from the D3DFVF_XYZRHW flag DWORD color; // from the D3DFVF_DIFFUSE flag}
Vértice CUSTOMVERTEX OurVertex = {320.0f, 50.0f,
1.0f, 1.0f, D3DCOLOR_XRGB(0, 0, 255)};
Outra possibilidade (trângulo) : CUSTOMVERTEX OurVertices[] ={ {320.0f, 50.0f, 1.0f, 1.0f, D3DCOLOR_XRGB(0, 0, 255),}, {520.0f, 400.0f, 1.0f, 1.0f, D3DCOLOR_XRGB(0, 255, 0),}, {120.0f, 400.0f, 1.0f, 1.0f, D3DCOLOR_XRGB(255, 0, 0),},};
Vertex Buffers Já temos o FVF e um triângulo. È necessário que
estejam prontos para uso do Direct3D Vertex buffer
Interface que armazena uma sessão em memória para manter informação sobre os vértices e modelos
HRESULT CreateVertexBuffer( UINT Length, // buffer lenght DWORD Usage, // special use flag DWORD FVF, // FVF built previously
D3DPOOL Pool, // where and how to create VB LPDIRECT3DVERTEXBUFFER9 ppVertexBuffer, // pointer HANDLE* pSharedHandle // null);
Construção LPDIRECT3DVERTEXBUFFER9 v_buffer;
d3ddev->CreateVertexBuffer(3*sizeof(CUSTOMVERTEX), 0, CUSTOMFVF, D3DPOOL_MANAGED, &v_buffer, NULL);
É necessário travar antes de acesso ao buffer Controle total da memória, e garantir que hardware de vídeo não mova memória.
Após, usar memcopy()
Funções HRESULT Lock(UINT OffsetToLock,
UINT SizeToLock, // lock part of the buffer VOID** ppbData, DWORD Flags // special ways to handle locked memory);
VOID* pVoid; // the void* we were talking about
v_buffer->Lock(0, 0, (void**)&pVoid, 0); // locks v_buffer, the buffer we made earlier
memcpy(pVoid, OurVertices, sizeof(OurVertices)); // copy vertices to the vertex buffer
v_buffer->Unlock(); // unlock v_buffer
Escrevendo a primitiva // this is the function used to render a single frame
void render_frame(void){ d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);
d3ddev->BeginScene();
// select which vertex format we are using d3ddev->SetFVF(CUSTOMFVF);
// select the vertex buffer to display d3ddev->SetStreamSource(0, v_buffer, 0, sizeof(CUSTOMVERTEX)); // number stream source, pointer vertex source, start, size
// copy the vertex buffer to the back buffer d3ddev->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1); //type, first vertex, number of primitives
d3ddev->EndScene();
d3ddev->Present(NULL, NULL, NULL, NULL);}
Lliberando VBs // this is the function that cleans up Direct3D and
COMvoid cleanD3D(void){ v_buffer->Release(); // close and release the vertex buffer d3ddev->Release(); // close and release the 3D device d3d->Release(); // close and release Direct3D}
Display: Direct3D - 1
Utilizado um vertexbuffer para desenhar tudo.Foi utilizado a propriedade DYNAMIC para
customizar detalhes dos vertices.
Display: Direct3D - 2 Desenhando:
Todas as texturas utilizam essa função para serem desenhadas, só mudando os valores dos parâmetros!
Projeto 2 – Tela inicial
Loading utilizando threads. Para que isso seja possível, setar D3DCREATE_MULTITHREADED no CreateDevice().