Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //--------------------------------------------------------------------------------------
- // File: DrawLineDemo.cpp
- //
- // Example: Draw line using D3D10
- //
- // Copyright (c) Stefan Petersson 2008. All rights reserved.
- //--------------------------------------------------------------------------------------
- #include "stdafx.h"
- #include "Lights.h"
- //--------------------------------------------------------------------------------------
- // Global Variables
- //--------------------------------------------------------------------------------------
- HINSTANCE g_hInst = NULL;
- HWND g_hWnd = NULL;
- D3D10_DRIVER_TYPE g_driverType = D3D10_DRIVER_TYPE_NULL;
- ID3D10Device* g_pd3dDevice = NULL;
- IDXGISwapChain* g_pSwapChain = NULL;
- ID3D10RenderTargetView* g_pRenderTargetView = NULL;
- ID3D10Texture2D* g_pDepthStencil = NULL;
- ID3D10DepthStencilView* g_pDepthStencilView = NULL;
- //camera data
- D3DXVECTOR3 g_vCameraPos = D3DXVECTOR3(0,0,-15);
- D3DXMATRIX g_mView;
- D3DXMATRIX g_mProj;
- //buffer data
- ID3D10InputLayout* g_pVertexLayout;
- ID3D10Buffer* g_pVB;
- //shader variables
- ID3D10Effect* g_pEffect;
- ID3D10EffectTechnique* g_pTechRenderLine;
- //Lights
- D3DXVECTOR4 ambientLight;
- DirectionalLight directionalLight;
- Material material;
- int m_VertexCount = 4;
- struct LineVertex
- {
- D3DXVECTOR3 pos;
- D3DXVECTOR4 color;
- D3DXVECTOR3 normal;
- D3DXVECTOR2 tc;
- LineVertex(D3DXVECTOR3 _pos, D3DXVECTOR4 _color, D3DXVECTOR3 _normal, D3DXVECTOR2 _tc)
- {
- pos = _pos;
- color = _color;
- normal = _normal;
- tc = _tc;
- }
- };
- //--------------------------------------------------------------------------------------
- // Forward declarations
- //--------------------------------------------------------------------------------------
- HRESULT InitWindow( HINSTANCE hInstance, int nCmdShow );
- LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
- HRESULT InitDevice();
- HRESULT Render(float deltaTime);
- void Update(float deltaTime);
- void CleanupDevice();
- //--------------------------------------------------------------------------------------
- // Create Direct3D device and swap chain
- //--------------------------------------------------------------------------------------
- HRESULT InitDevice()
- {
- HRESULT hr = S_OK;;
- RECT rc;
- GetClientRect( g_hWnd, &rc );
- UINT width = rc.right - rc.left;
- UINT height = rc.bottom - rc.top;
- UINT createDeviceFlags = 0;
- #ifdef _DEBUG
- createDeviceFlags |= D3D10_CREATE_DEVICE_DEBUG;
- #endif
- D3D10_DRIVER_TYPE driverTypes[] =
- {
- D3D10_DRIVER_TYPE_HARDWARE,
- D3D10_DRIVER_TYPE_REFERENCE,
- };
- UINT numDriverTypes = sizeof(driverTypes) / sizeof(driverTypes[0]);
- DXGI_SWAP_CHAIN_DESC sd;
- ZeroMemory( &sd, sizeof(sd) );
- sd.BufferCount = 1;
- sd.BufferDesc.Width = width;
- sd.BufferDesc.Height = height;
- sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
- sd.BufferDesc.RefreshRate.Numerator = 60;
- sd.BufferDesc.RefreshRate.Denominator = 1;
- sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
- sd.OutputWindow = g_hWnd;
- sd.SampleDesc.Count = 1;
- sd.SampleDesc.Quality = 0;
- sd.Windowed = TRUE;
- for( UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++ )
- {
- g_driverType = driverTypes[driverTypeIndex];
- hr = D3D10CreateDeviceAndSwapChain( NULL, g_driverType, NULL, createDeviceFlags,
- D3D10_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice );
- if( SUCCEEDED( hr ) )
- break;
- }
- if( FAILED(hr) )
- return hr;
- // Create a render target view
- ID3D10Texture2D* pBackBuffer;
- hr = g_pSwapChain->GetBuffer( 0, __uuidof( ID3D10Texture2D ), (LPVOID*)&pBackBuffer );
- if( FAILED(hr) )
- return hr;
- hr = g_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &g_pRenderTargetView );
- pBackBuffer->Release();
- if( FAILED(hr) )
- return hr;
- // Create depth stencil texture
- D3D10_TEXTURE2D_DESC descDepth;
- descDepth.Width = width;
- descDepth.Height = height;
- descDepth.MipLevels = 1;
- descDepth.ArraySize = 1;
- descDepth.Format = DXGI_FORMAT_D32_FLOAT;
- descDepth.SampleDesc.Count = 1;
- descDepth.SampleDesc.Quality = 0;
- descDepth.Usage = D3D10_USAGE_DEFAULT;
- descDepth.BindFlags = D3D10_BIND_DEPTH_STENCIL;
- descDepth.CPUAccessFlags = 0;
- descDepth.MiscFlags = 0;
- hr = g_pd3dDevice->CreateTexture2D( &descDepth, NULL, &g_pDepthStencil );
- if( FAILED(hr) )
- return hr;
- // Create the depth stencil view
- D3D10_DEPTH_STENCIL_VIEW_DESC descDSV;
- descDSV.Format = descDepth.Format;
- descDSV.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2D;
- descDSV.Texture2D.MipSlice = 0;
- hr = g_pd3dDevice->CreateDepthStencilView( g_pDepthStencil, &descDSV, &g_pDepthStencilView );
- if( FAILED(hr) )
- return hr;
- g_pd3dDevice->OMSetRenderTargets( 1, &g_pRenderTargetView, g_pDepthStencilView );
- // Setup the viewport
- D3D10_VIEWPORT vp;
- vp.Width = width;
- vp.Height = height;
- vp.MinDepth = 0.0f;
- vp.MaxDepth = 1.0f;
- vp.TopLeftX = 0;
- vp.TopLeftY = 0;
- g_pd3dDevice->RSSetViewports( 1, &vp );
- //Create vertex buffer to hold maxAmount of particles
- D3D10_BUFFER_DESC bd;
- bd.Usage = D3D10_USAGE_DYNAMIC;
- bd.ByteWidth = sizeof( LineVertex ) * m_VertexCount;
- bd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
- bd.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
- bd.MiscFlags = 0;
- if( FAILED( g_pd3dDevice->CreateBuffer( &bd, 0, &g_pVB ) ) )
- MessageBox( 0, "Unable to create Vertex Buffer", "VB Error", 0 );
- //Init shader effect
- DWORD dwShaderFlags = D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY;
- if(FAILED(D3DX10CreateEffectFromFile( "Line.fx",
- NULL,
- NULL,
- "fx_4_0",
- dwShaderFlags,
- 0,
- g_pd3dDevice,
- NULL,
- NULL,
- &g_pEffect,
- NULL,
- NULL)))
- {
- MessageBox(0, "Error compiling shader!", "Shader error!", 0);
- }
- g_pTechRenderLine = g_pEffect->GetTechniqueByName("DrawLine");
- // Define our vertex data layout
- const D3D10_INPUT_ELEMENT_DESC lineVertexLayout[] =
- {
- { "POS", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
- { "COL", 0, DXGI_FORMAT_R32G32B32A32_FLOAT,0,12,D3D10_INPUT_PER_VERTEX_DATA, 0 },
- { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 28, D3D10_INPUT_PER_VERTEX_DATA, 0 },
- { "TC", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 40, D3D10_INPUT_PER_VERTEX_DATA, 0 }
- };
- D3D10_PASS_DESC PassDesc;
- g_pTechRenderLine->GetPassByIndex(0)->GetDesc(&PassDesc);
- //Create Input Layout (== Vertex Declaration)
- g_pd3dDevice->CreateInputLayout(lineVertexLayout,
- sizeof(lineVertexLayout) / sizeof(D3D10_INPUT_ELEMENT_DESC),
- PassDesc.pIAInputSignature,
- PassDesc.IAInputSignatureSize,
- &g_pVertexLayout );
- //SETTING TEXTURE
- ID3D10ShaderResourceView* mDiffuseMapRV;
- D3DX10CreateShaderResourceViewFromFile(g_pd3dDevice,"bigskull.png", 0, 0, &mDiffuseMapRV, 0 );
- ID3D10EffectShaderResourceVariable* mfxDiffuseMapVar;
- mfxDiffuseMapVar = g_pEffect->GetVariableByName(
- "gDiffuseMap")->AsShaderResource();
- // Set the C++ texture resource view to the effect texture variable.
- mfxDiffuseMapVar->SetResource(mDiffuseMapRV);
- return S_OK;
- }
- void Map(void** b)
- {
- g_pVB->Map( D3D10_MAP_WRITE_DISCARD, 0, reinterpret_cast< void** >(b) );
- }
- void Update(float deltaTime)
- {
- LineVertex* pData = NULL;
- //if( SUCCEEDED( g_pVB->Map( D3D10_MAP_WRITE_DISCARD, 0, reinterpret_cast< void** >(&pData) ) ) )
- //{
- Map((void**)&pData);
- pData[0].pos = D3DXVECTOR3(0,3,0);
- pData[1].pos = D3DXVECTOR3(0,0,0);
- pData[2].pos = D3DXVECTOR3(3,3,0);
- pData[3].pos = D3DXVECTOR3(3,0,0);
- pData[0].tc = D3DXVECTOR2(0,0);
- pData[1].tc = D3DXVECTOR2(0,1);
- pData[2].tc = D3DXVECTOR2(1,0);
- pData[3].tc = D3DXVECTOR2(1,1);
- for(int i = 0; i < m_VertexCount; i++)
- {
- pData[i].color = D3DXVECTOR4(pData[i].pos , 0.1f);
- pData[i].normal = D3DXVECTOR3(0,0,1);
- }
- //CREATE LIGHTS AND MATERIAL
- //--------------------------------------------------------------------------------
- ambientLight = D3DXVECTOR4(1.0f,1.0f,1.0f,1.0f);
- //set directional light - MAKE sure light direction is a unit vector
- directionalLight.color = D3DXVECTOR4(1.0f,1.0f,1.0f,1.0f);
- directionalLight.direction = D3DXVECTOR3(0,0,1);
- D3DXVec3Normalize(&directionalLight.direction, &directionalLight.direction);
- material.ambient = 0.1f;
- material.diffuse = 0.5f;
- material.specular = 0.5f;
- material.shininess = 30;
- //set variables
- ID3D10EffectVariable* pVar = g_pEffect->GetVariableByName( "light" );
- pVar->SetRawValue(&directionalLight, 0, sizeof(DirectionalLight));
- pVar = g_pEffect->GetVariableByName( "material" );
- pVar->SetRawValue(&material, 0, sizeof(Material));
- pVar = g_pEffect->GetVariableByName( "ambientLight" );
- pVar->SetRawValue( &ambientLight, 0, 16 );
- PointLight herp;
- herp.ambient = D3DXCOLOR(0.4f, 0.4f, 0.4f, 1.0f);
- herp.diffuse = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
- herp.spec = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
- herp.attenuation = D3DXVECTOR3(0.0f,0.1f,0.0f);
- herp.range = 50.0f;
- herp.Pos = D3DXVECTOR3(0,0,0);
- g_pEffect->GetVariableByName("derp")->SetRawValue(&herp, 0, sizeof(herp));
- g_pVB->Unmap();
- }
- HRESULT Render(float deltaTime)
- {
- // Render the result
- D3DXMATRIX mWorldViewProj;
- //RECT rc;
- float width = 1024;
- float height = 768;
- //calculate WVP matrix
- static float rotY = 0.0f;
- rotY += deltaTime;
- D3DXMATRIX world, view, proj;
- D3DXMatrixRotationY(&world, rotY);
- D3DXMatrixLookAtLH(&view, &g_vCameraPos, &D3DXVECTOR3(0,0,0), &D3DXVECTOR3(0,1,0));
- D3DXMatrixPerspectiveFovLH(&proj, (float)D3DX_PI * 0.45f, 1024.0f / 768.0f, 1.0f, 100.0f);
- mWorldViewProj = world * view * proj;
- // Set variables
- g_pEffect->GetVariableByName( "g_mWorldViewProjection" )->AsMatrix()->SetMatrix( (float*)&mWorldViewProj );
- g_pEffect->GetVariableByName("CameraPos")->AsVector()->SetFloatVector((float*)&g_vCameraPos);
- //create matrix effect pointers
- g_pEffect->GetVariableByName( "View" )->AsMatrix()->SetMatrix((float*)&view);
- g_pEffect->GetVariableByName( "Projection" )->AsMatrix()->SetMatrix((float*)&proj);
- g_pEffect->GetVariableByName( "World" )->AsMatrix()->SetMatrix((float*)&world);
- // Set Input Assembler params
- UINT stride = sizeof(LineVertex);
- UINT offset = 0;
- g_pd3dDevice->IASetInputLayout( g_pVertexLayout );
- g_pd3dDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP );
- g_pd3dDevice->IASetVertexBuffers( 0, 1, &g_pVB, &stride, &offset );
- static float ClearColor[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
- //clear render target
- g_pd3dDevice->ClearRenderTargetView( g_pRenderTargetView, ClearColor );
- //clear depth info
- g_pd3dDevice->ClearDepthStencilView( g_pDepthStencilView, D3D10_CLEAR_DEPTH, 1.0f, 0 );
- // Render line using the technique g_pRenderTextured
- D3D10_TECHNIQUE_DESC techDesc;
- g_pTechRenderLine->GetDesc( &techDesc );
- for( UINT p = 0; p < techDesc.Passes; p++ )
- {
- g_pTechRenderLine->GetPassByIndex( p )->Apply(0);
- g_pd3dDevice->Draw(m_VertexCount, 0);
- }
- if(FAILED(g_pSwapChain->Present( 0, 0 )))
- return E_FAIL;
- return S_OK;
- }
- //--------------------------------------------------------------------------------------
- // Entry point to the program. Initializes everything and goes into a message processing
- // loop. Idle time is used to render the scene.
- //--------------------------------------------------------------------------------------
- int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow )
- {
- if( FAILED( InitWindow( hInstance, nCmdShow ) ) )
- return 0;
- if( FAILED( InitDevice() ) )
- return 0;
- __int64 cntsPerSec = 0;
- QueryPerformanceFrequency((LARGE_INTEGER*)&cntsPerSec);
- float secsPerCnt = 1.0f / (float)cntsPerSec;
- __int64 prevTimeStamp = 0;
- QueryPerformanceCounter((LARGE_INTEGER*)&prevTimeStamp);
- // Main message loop
- MSG msg = {0};
- while(WM_QUIT != msg.message)
- {
- if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE) )
- {
- TranslateMessage( &msg );
- DispatchMessage( &msg );
- }
- else
- {
- __int64 currTimeStamp = 0;
- QueryPerformanceCounter((LARGE_INTEGER*)&currTimeStamp);
- float dt = (currTimeStamp - prevTimeStamp) * secsPerCnt;
- //render
- Update(dt);
- Render(dt);
- prevTimeStamp = currTimeStamp;
- }
- }
- CleanupDevice();
- return (int) msg.wParam;
- }
- //--------------------------------------------------------------------------------------
- // Register class and create window
- //--------------------------------------------------------------------------------------
- HRESULT InitWindow( HINSTANCE hInstance, int nCmdShow )
- {
- // Register class
- WNDCLASSEX wcex;
- wcex.cbSize = sizeof(WNDCLASSEX);
- wcex.style = CS_HREDRAW | CS_VREDRAW;
- wcex.lpfnWndProc = WndProc;
- wcex.cbClsExtra = 0;
- wcex.cbWndExtra = 0;
- wcex.hInstance = hInstance;
- wcex.hIcon = 0;
- wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
- wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
- wcex.lpszMenuName = NULL;
- wcex.lpszClassName = "D3DLines";
- wcex.hIconSm = 0;
- if( !RegisterClassEx(&wcex) )
- return E_FAIL;
- // Create window
- g_hInst = hInstance;
- RECT rc = { 0, 0, 1024, 768 };
- AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, FALSE );
- if(!(g_hWnd = CreateWindow( "D3DLines",
- "Direct3D 10 : Line Drawing",
- WS_OVERLAPPEDWINDOW,
- CW_USEDEFAULT,
- CW_USEDEFAULT,
- rc.right - rc.left,
- rc.bottom - rc.top,
- NULL,
- NULL,
- hInstance,
- NULL)))
- {
- return E_FAIL;
- }
- ShowWindow( g_hWnd, nCmdShow );
- return S_OK;
- }
- //--------------------------------------------------------------------------------------
- // Called every time the application receives a message
- //--------------------------------------------------------------------------------------
- LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
- {
- PAINTSTRUCT ps;
- HDC hdc;
- switch (message)
- {
- case WM_PAINT:
- hdc = BeginPaint(hWnd, &ps);
- EndPaint(hWnd, &ps);
- break;
- case WM_DESTROY:
- PostQuitMessage(0);
- break;
- case WM_KEYDOWN:
- switch(wParam)
- {
- case VK_ESCAPE:
- PostQuitMessage(0);
- break;
- }
- break;
- default:
- return DefWindowProc(hWnd, message, wParam, lParam);
- }
- return 0;
- }
- //--------------------------------------------------------------------------------------
- // Clean up the objects we've created
- //--------------------------------------------------------------------------------------
- void CleanupDevice()
- {
- if( g_pd3dDevice ) g_pd3dDevice->ClearState();
- SAFE_RELEASE(g_pRenderTargetView);
- SAFE_RELEASE(g_pDepthStencilView);
- SAFE_RELEASE(g_pSwapChain);
- SAFE_RELEASE(g_pd3dDevice);
- SAFE_RELEASE(g_pVB);
- }
Add Comment
Please, Sign In to add comment