Two days to learn DirectX the next day

Source: Internet
Author: User

Feed

A few days ago a simple run of a DirectX 9 program, thinking that DirectX is so drawn, the facts proved a bit naive.

The previous program was at best a fixed-line thing. But today we're going to use DirectX11 to write a small frame.

Dragon Book Don't Look, see Introduction to 3D GAME programming with directx®11
A few important classes

Id3d11device: A virtual adapter that is used to run rendering and create resources.

Id3d11devicecontext: represents a device context which generates rendering commands.

Id3d11rendertargetview: identifies the Render-target subresources that can be accessed during rendering.

id3d11inputlayout: An Input-layout interface holds a definition of what to feed vertex data that's laid out in memory into the input-assemble R stage of the graphics pipeline.


Rendering Pipeline (translated from Microsoft documentation)




The DirectX programming pipeline is designed for real-time game applications and shows the flow of data from each stage of input to output. Compared to DirectX10 's graphics pipeline, DirectX11 added some additional stages to support some of the new features.

You can use DirectX 11API to configure all stages, which can be set in HLSL language so that the entire pipeline has a very large scalability and adaptability. Here is a list of what happens at each stage.

Input-assembler Stage : Provides data for rendering (triangles, lines, points);

vertex-shader Stage: Handles vertices, usually in the following operations: Transformmation, skinning, lighting calculations. Typically a vertexshader input is a set of vertices, and the output is a set of vertices.

Geometry-shader Statge: This stage handles all the elements, the input is the complete entity (the triangle is three vertices, the line segment is two vertices, and there is a single point). In addition, each entity can contain information about adjacent elements. In addition, this stage can be simplified and refined for some elements. Given an entity, geometry shader can discard this entity, or it can generate a new one or more entities.

stream-outputStage: Data streamed from the previous stage, you can put the element information from the pipeline into the storage, or into the rasterizer phase. The data that is put into memory can be placed in the pipeline again, or read by the CPU.

Rasterizer Stage: Crop The elements, prepare the elements for pixel shader, and prepare to invoke pixel shader.

pixel-shader Stage: Receives the interpolated result, generating the final image.

Output-merger Stage : Merges various types of output information (pixel shader value, depth information, stencil value), and the depth/stencil cache of the current render target, resulting in the final pipelined result.

tessellationStage: This phase is composed of Hull-shader, Tessellator, and Domain-shader, which mainly converts the high-order surface into a series of triangular rows, which are then placed in the assembly line.


Direct3D 11 programmable pipelining can also be used for high-speed computing tasks, and a compute shader can be used for general GPU computing with DIRECT3D11 extensions.


Draw a triangle with shader

Direct3D, we need to complete the following several steps:

1. Define the type of equipment we need to check (device types) and feature level (feature levels)

2. Create Direct3D devices, render devices (context) and swap chains (swap chain).

3. Create a render target.

4. Setting the viewport (viewport)

5. Start rendering

6. Rendering the Model

7. Clear the screen

Code Listing

Include the basic Windows header files and the Direct3D header Files#include <windows.h> #include &LT;WINDOWSX.H&G T, #include <d3d11.h> #include <d3dx11.h> #include <d3dx10.h> #include "assimpmodel.h"//Include the Direct3D Library File#pragma Comment (lib, "D3d11.lib") #pragma comment (lib, "D3dx11.lib") #pragma comment (lib, "D3dx10.l  IB ")//define the screen resolution#define screen_width 800#define screen_height 600//Global Declarationsidxgiswapchain             *swapchain;                     The pointer to the swap chain Interfaceid3d11device *dev;           The pointer to our Direct3D device Interfaceid3d11devicecontext *devcon;    The pointer to our Direct3D device Contextid3d11rendertargetview *backbuffer;            The pointer to we back bufferid3d11inputlayout *playout;               The pointer to the input layoutid3d11vertexshader *pvs;                The pointer to the vertex shaderid3d11pixelshader *pps; The pointer to the PixeL Shaderid3d11buffer *pvbuffer; The pointer to the vertex buffer//a struct-define a single vertexstruct vertex{D3DXVECTOR3 position; D3dxcolor Color;    };//function Prototypesvoid INITD3D (HWND hwnd);     Sets up and initializes direct3dvoid renderframe (void);        Renders a single framevoid cleand3d (void);    Closes Direct3D and releases memoryvoid initgraphics (void);    Creates the shape to rendervoid initpipeline (void); Loads and prepares the shaders//the WindowProc function Prototypelresult CALLBACK WindowProc (HWND hwnd, UINT message, WPARAM WPARAM, LPARAM LPARAM);//The entry point for any Windows programint WINAPI WinMain (hinstance hinstance,hinstance H Previnstance,lpstr Lpcmdline,int nCmdShow) {HWND hwnd; Wndclassex WC; ZeroMemory (&AMP;WC, sizeof (wndclassex)); wc.cbsize = sizeof (wndclassex); Wc.style = Cs_hredraw | Cs_vredraw;wc.lpfnwndproc = Windowproc;wc.hinstance = Hinstance;wc.hcursor = LoadCursor (NULL, IDC_ARROW); Wc.lpszclassname = "WindOwclass "; RegisterClassEx (&AMP;WC); RECT WR = {0, 0, screen_width, screen_height}; Adjustwindowrect (&AMP;WR, Ws_overlappedwindow, FALSE); hWnd = CreateWindowEx (NULL, "Windowclass", "Triangle", Ws_ Overlappedwindow,300,300,wr.right-wr.left,wr.bottom-wr.top,null,null,hinstance,null); ShowWindow (hwnd, ncmdshow);//Set up and initialize DIRECT3DINITD3D (HWND);//Enter the main loop:msg msg;while (TRUE) {if ( PeekMessage (&msg, NULL, 0, 0, pm_remove)) {TranslateMessage (&msg);D ispatchmessage (&msg); if (msg.message = = Wm_quit) break;} Renderframe ();} Clean up DirectX and Comcleand3d (); return msg.wparam;} This is the main message handler for the Programlresult CALLBACK WindowProc (HWND hwnd, UINT message, WPARAM WPARAM, LPA   RAM lParam) {switch (message) {case wm_destroy:{postquitmessage (0); return 0;} break;} Return DefWindowProc (hWnd, message, WParam, LParam);} This function initializes and prepares Direct3D for Usevoid Initd3d (HWND hwnd) {//Create a struct-to-hold information a Bout thE swap Chaindxgi_swap_chain_desc scd;//clear out the struct for usezeromemory (&AMP;SCD, sizeof (DXGI_SWAP_CHAIN_DESC)); /fill the swap chain description structscd.                                   BufferCount = 1; One back BUFFERSCD.    Bufferdesc.format = Dxgi_format_r8g8b8a8_unorm; Use 32-bit colorscd.                   Bufferdesc.width = Screen_width; Set the back buffer widthscd.                 Bufferdesc.height = Screen_height; Set the back buffer heightscd.     Bufferusage = Dxgi_usage_render_target_output; How swap chain are to be usedscd.                               OutputWindow = hWnd; The window to be USEDSCD.                              Sampledesc.count = 4; How many multisamplesscd.                                   windowed = TRUE; Windowed/full-screen MODESCD.    Flags = Dxgi_swap_chain_flag_allow_mode_switch; Allow Full-screen switching//Create a device, device context and swap chain using the information in the SCD STRUCTD3D 11CreateDeviceAndSwapCHain (null,d3d_driver_type_hardware,null,null,null,null,d3d11_sdk_version,&scd,&swapchain,&dev,null , &devcon);//Get the address of the back bufferid3d11texture2d *pbackbuffer;swapchain->getbuffer (0, __uuidof ( id3d11texture2d), (lpvoid*) &pbackbuffer);//Use the back buffer address to create the render Targetdev->createrend Ertargetview (Pbackbuffer, NULL, &backbuffer);p backbuffer->release ();//Set the render target as the back Bufferdevcon->omsetrendertargets (1, &backbuffer, NULL);//Set the Viewportd3d11_viewport VIEWPORT; ZeroMemory (&viewport, sizeof (D3d11_viewport)); viewport. TOPLEFTX = 0;viewport. Toplefty = 0;viewport. Width = Screen_width;viewport. Height = Screen_height;devcon->rssetviewports (1, &viewport); Initpipeline (); Initgraphics ();} The the function used to render a single framevoid renderframe (void) {//clear the back buffer to a deep bluedevcon- >clearrendertargetview (Backbuffer, D3dxcolor (0.0f, 0.2f, 0.4f, 1.0f));//Selectwhich vertex buffer to displayuint stride = sizeof (vertex); UINT offset = 0;devcon->iasetvertexbuffers (0, 1, &pvbuffer, &stride, &offset);//select which Primtive typ E We are usingdevcon->iasetprimitivetopology (d3d10_primitive_topology_trianglelist);//Draw the vertex buffer to the Back Bufferdevcon->draw (3, 0);//Switch the back buffer and the front bufferswapchain->present (0, 0);}    This is the function of the cleans up Direct3D and Comvoid cleand3d (void) {swapchain->setfullscreenstate (FALSE, NULL); Switch to windowed mode//Close and release all existing COM objectsplayout->release ();p vs->release ();pP s-> Release ();p vbuffer->release (); Swapchain->release (); Backbuffer->release ();d ev->release ();d evcon- >release ();} This is the function of the creates the shape to Rendervoid initgraphics () {//assimpmodel *model = new Assimpmodel ();//mod El->initialize (dev);//Create a triangle using the VERTEX Structvertex ourvertices[] ={{D3dxvector3 (0.0f, 0.5f, 0.0f), D3dxcolor (1.0f, 0.0f, 0.0f, 1.0f)},{D3dxvector3 (0.45f, -0.5, 0.0f), D3dxcolor (0.0f, 1.0f, 0.0f, 1.0f) },{D3dxvector3 ( -0.45f, -0.5f, 0.0f), D3dxcolor (0.0f, 0.0f, 1.0f, 1.0f)}};//Create the vertex bufferd3d11_buffer_desc b D ZeroMemory (&AMP;BD, sizeof (BD)); Bd.                Usage = d3d11_usage_dynamic;             Write access access by CPU and gpubd.bytewidth = sizeof (VERTEX) * 3; Size is the VERTEX struct * 3bd.       Bindflags = D3d11_bind_vertex_buffer; Use as a vertex bufferbd.    Cpuaccessflags = D3d11_cpu_access_write;       Allow CPU to write in Bufferdev->createbuffer (&AMP;BD, NULL, &pvbuffer); Create the buffer//copy the vertices into the Bufferd3d11_mapped_subresource ms;devcon->map (Pvbuffer, NULL, d3d11_m    Ap_write_discard, NULL, &ms);                 Map the buffermemcpy (ms.pdata, ourvertices, sizeof (ourvertices));                                      Copy the Datadevcon->unmap (Pvbuffer, NULL); Unmap the buffer}//This function loads and prepares the shadersvoid Initpipeline () {//load and compile the Shadersid3d10blob *vs, *ps;d 3dx11compilefromfile ("Shaders.shader", 0, 0, "Vshader", "Vs_5_0", 0, 0, 0, &vs, 0, 0);D 3dx11compilefromfile ("Shaders . Shader ", 0, 0," Pshader "," Ps_5_0 ", 0, 0, 0, &ps, 0, 0);//encapsulate both shaders into shader objectsdev->create VertexShader (Vs->getbufferpointer (), Vs->getbuffersize (), NULL, &pvs);d Ev->createpixelshader (PS-> GetBufferPointer (), Ps->getbuffersize (), NULL, &pps);//Set the shader Objectsdevcon->vssetshader (PVS, 0, 0); Devcon->pssetshader (PPS, 0, 0);//Create the input layout Objectd3d11_input_element_desc ied[] ={{"POSITION", 0, Dxgi_ Format_r32g32b32_float, 0, 0, d3d11_input_per_vertex_data, 0},{"COLOR", 0, dxgi_format_r32g32b32a32_float, 0, D3D11 _input_per_vertex_data, 0},};d ev->createinputlayout (IED, 2, Vs->getbufferpointer (), Vs->getbuffersize (), &playout);d Evcon->iasetinputlayout (PLayOut);} 


Shader.shader

struct vout{    float4 position:sv_position;    Float4 Color:color;}; Vout Vshader (float4 position:position, Float4 color:color) {    vout output;    Output.position = position;    Output.color = color;    return output;} Float4 Pshader (float4 position:sv_position, Float4 color:color): sv_target{    return color;}

The code is not detailed, you can see the reference link.

The results are as follows



Encapsulates a simple frame

It's not so good to write all the code in Main.cpp, it's best to abstract the various types by function. The following is a framework written in reference to the tutorial.



A simple frame, or a small triangle to render, but it is pumping a lot of classes out, such as cameras, input and the like, the extension behind.

Of course, it's a more groove frame, huh.

Code to see GitHub directly.


Reference

Graphics pipeline-https://msdn.microsoft.com/en-us/library/windows/desktop/ff476882 (v=vs.85). aspx

"Introduction to 3D GAME programming with Directx®11"

DirectX tutorials-http://www.rastertek.com/tutdx11.html

Http://www.directxtutorial.com/default.aspx

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Two days to learn DirectX the next day

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.