欢迎访问 生活随笔!

尊龙游戏旗舰厅官网

当前位置: 尊龙游戏旗舰厅官网 > 编程资源 > 编程问答 >内容正文

编程问答

【directx12】2.示例三角形绘制 -尊龙游戏旗舰厅官网

发布时间:2024/9/30 编程问答 19 豆豆
尊龙游戏旗舰厅官网 收集整理的这篇文章主要介绍了 【directx12】2.示例三角形绘制 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

1.效果

下面只贴出关于dx的代码,有时间再详细说明。

2.标头.h

#pragma once#include "pch.h" #include "lvedebug.h" #include "lvesystem.h"#include #include "d3dx12.h" #include #include #include using namespace directx;typedef idxgifactory7 _idxgifactory; typedef idxgiadapter4 _idxgiadapter; typedef idxgiswapchain4 _idxgiswapchain; namespace lve {void gethardwareadapter(_idxgifactory* pfactory, _idxgiadapter** ppadapter);const int swap_chain_buffer_count = 2;//此值不能小于2class directx{public://pipelinecom_ptr<_idxgifactory> _factory;com_ptr<_idxgiadapter> _adapter;com_ptr _device;com_ptr _commandqueue;com_ptr<_idxgiswapchain> _swapchain;com_ptr _rtvheap;uint _rtvdescriptorsize;com_ptr _rendertargets[swap_chain_buffer_count];com_ptr _commandallocator;//assetscom_ptr _rootsignature;com_ptr _pipelinestate;com_ptr _commandlist;com_ptr _vertexbuffer;d3d12_vertex_buffer_view _vertexbufferview;//synchronization objects.uint _frameindex;handle _fenceevent;com_ptr _fence;uint64 _fencevalue;d3d12_viewport _viewport;d3d12_rect _scissorrect;void init();void update();void render();void release();private:struct vertex{xmfloat3 position;xmfloat4 color;};void _init_pre(){if (!xmverifycpusupport()){g_debug.line(l"directxmath does not support the current platform!");return;}}void _init_pipeline(){ #if defined(_debug)_init_debug_layer(); #endif_init_dxgi();_init_device();_init_command_queue();_init_swap_chain();_init_descriptor_heap();_init_render_target_view();_init_command_allocator();}void _init_debug_layer();void _init_dxgi();void _init_device();void _init_command_queue();void _init_swap_chain();void _init_descriptor_heap();void _init_render_target_view();void _init_command_allocator();//void _init_assets(){_init_root_signature();_init_graphics_pipeline_state();_init_command_list();_init_vertex_buffer();_init_fence();}void _init_root_signature();void _init_graphics_pipeline_state();void _init_command_list();void _init_vertex_buffer();void _init_fence();void waitforpreviousframe();void populatecommandlist();};extern directx g_dx; }

3.源.cpp

#include "lvedirectx.h"namespace lve {directx g_dx;void directx::init(){_init_pre();//load pipeline_init_pipeline();//load assets_init_assets();_viewport.height = 600;_viewport.maxdepth = 1.0f;_viewport.mindepth = 0;_viewport.topleftx = 0;_viewport.toplefty = 0;_viewport.width = 800;_scissorrect.bottom = 600;_scissorrect.left = 0;_scissorrect.right = 800;_scissorrect.top = 0;}void directx::update(){}void directx::render(){// record all the commands we need to render the scene into the command list.populatecommandlist();// execute the command list.id3d12commandlist* ppcommandlists[] = { _commandlist.get() };_commandqueue->executecommandlists(_countof(ppcommandlists), ppcommandlists);// present the frame.hresult hr = _swapchain->present(1, 0);if (failed(hr)){g_debug.line(l"failed to present frame!");return;}waitforpreviousframe();}void directx::release(){// wait for the gpu to be done with all resources.waitforpreviousframe();closehandle(_fenceevent);}void directx::_init_debug_layer(){// enable the d3d12 debug layer.com_ptr debugcontroller;hresult hr = d3d12getdebuginterface(iid_ppv_args(&debugcontroller));if (failed(hr)){g_debug.line(l"failed to create debug layer!");return;}debugcontroller->enabledebuglayer();}void directx::_init_dxgi(){hresult hr = createdxgifactory1(__uuidof(_idxgifactory), (void**)(&_factory));if (failed(hr)){g_debug.line(l"failed to create dxgi factory!");return;}}void directx::_init_device(){_idxgiadapter* adapter;gethardwareadapter(_factory.get(), &adapter);if (adapter == nullptr){g_debug.line(l"failed to enumerate hardware adapter!");return;}_adapter.attach(adapter);hresult hr = d3d12createdevice(_adapter.get(),d3d_feature_level_11_0,iid_ppv_args(&_device));if (failed(hr)){g_debug.line(l"failed to create device!");return;}}void directx::_init_command_queue(){d3d12_command_queue_desc desc;desc.flags = d3d12_command_queue_flag_none;desc.nodemask = 0;desc.priority = d3d12_command_queue_priority_normal;desc.type = d3d12_command_list_type_direct;hresult hr = _device->createcommandqueue(&desc, iid_ppv_args(&_commandqueue));if (failed(hr)){g_debug.line(l"failed to create command queue!");return;}}void directx::_init_swap_chain(){com_ptr swapchain;dxgi_swap_chain_desc desc;desc.buffercount = swap_chain_buffer_count;desc.bufferdesc.format = dxgi_format_r8g8b8a8_unorm;desc.bufferdesc.height = 600;desc.bufferdesc.refreshrate.denominator = 0;desc.bufferdesc.refreshrate.numerator = 0;desc.bufferdesc.scaling = dxgi_mode_scaling_unspecified;desc.bufferdesc.scanlineordering = dxgi_mode_scanline_order_unspecified;desc.bufferdesc.width = 800;desc.bufferusage = dxgi_usage_render_target_output;desc.flags = 0;desc.outputwindow = g_system.gethwnd();desc.sampledesc.count = 1;desc.sampledesc.quality = 0;desc.swapeffect = dxgi_swap_effect_flip_discard;desc.windowed = true;hresult hr = _factory->createswapchain(_commandqueue.get(),&desc,swapchain.put());/*dxgi_swap_chain_desc1 desc;desc.alphamode = dxgi_alpha_mode_unspecified;desc.buffercount = swap_chain_buffer_count;desc.bufferusage = dxgi_usage_render_target_output;desc.flags = 0;desc.format = dxgi_format_r8g8b8a8_unorm; desc.height = 600;desc.sampledesc.count = 1;desc.sampledesc.quality = 0;desc.scaling = dxgi_scaling_none;desc.stereo = false;desc.swapeffect = dxgi_swap_effect_flip_discard;desc.width = 800;//dxgi_swap_chain_fullscreen_desc desc_full;hresult hr = _factory->createswapchainforhwnd(_commandqueue.get(),// for direct3d 12, this is a pointer to a direct command queue, and not to the device.g_system.gethwnd(),&desc,nullptr,nullptr,swapchain.put());*/if (failed(hr)){g_debug.line(l"failed to create swap chain!");return;}swapchain.as(_swapchain);}void directx::_init_descriptor_heap(){d3d12_descriptor_heap_desc desc;desc.flags = d3d12_descriptor_heap_flag_none;desc.nodemask = 0;desc.numdescriptors = swap_chain_buffer_count;//desc.type = d3d12_descriptor_heap_type_rtv;hresult hr = _device->createdescriptorheap(&desc, iid_ppv_args(&_rtvheap));if (failed(hr)){g_debug.line(l"failed to create descriptor heap!");return;}_rtvdescriptorsize = _device->getdescriptorhandleincrementsize(d3d12_descriptor_heap_type_rtv);}void directx::_init_render_target_view(){uint m_rtvdescriptorsize = _device->getdescriptorhandleincrementsize(d3d12_descriptor_heap_type_rtv);// create frame resources.//d3d12_cpu_descriptor_handle rtvhandle = _rtvheap->getcpudescriptorhandleforheapstart();cd3dx12_cpu_descriptor_handle rtvhandle(_rtvheap->getcpudescriptorhandleforheapstart());// create a rtv for each frame.for (uint n = 0; n < swap_chain_buffer_count; n ){hresult hr = _swapchain->getbuffer(n, iid_ppv_args(&_rendertargets[n]));if (failed(hr)){g_debug.line(l"failed to get buffer from the swap chain!");continue;}_device->createrendertargetview(_rendertargets[n].get(), nullptr, rtvhandle);rtvhandle.offset(1, m_rtvdescriptorsize);}}void directx::_init_command_allocator(){hresult hr = _device->createcommandallocator(d3d12_command_list_type_direct, iid_ppv_args(&_commandallocator));if (failed(hr)){g_debug.line(l"failed to create command allocator!");return;}}void directx::_init_root_signature(){cd3dx12_root_signature_desc rootsignaturedesc;rootsignaturedesc.init(0, nullptr, 0, nullptr, d3d12_root_signature_flag_allow_input_assembler_input_layout);id3dblob* signature;id3dblob* error;hresult hr = d3d12serializerootsignature(&rootsignaturedesc, d3d_root_signature_version_1, &signature, &error);if (failed(hr)){g_debug.line(l"failed to serialize root signature!");return;}hr = _device->createrootsignature(0, signature->getbufferpointer(), signature->getbuffersize(), iid_ppv_args(&_rootsignature));if (failed(hr)){g_debug.line(l"failed to serialize root signature!");return;}}void directx::_init_graphics_pipeline_state(){com_ptr vertexshader;com_ptr pixelshader;#if defined(_debug)// enable better shader debugging with the graphics debugging tools.uint compileflags = d3dcompile_debug | d3dcompile_skip_optimization; #elseuint compileflags = 0; #endifhresult hr = d3dcompilefromfile(l"shaders.hlsl", nullptr, nullptr, "vsmain", "vs_5_0", compileflags, 0, vertexshader.put(), nullptr);if (failed(hr)){g_debug.line(l"failed to compile vertex shader!");return;}hr = d3dcompilefromfile(l"shaders.hlsl", nullptr, nullptr, "psmain", "ps_5_0", compileflags, 0, pixelshader.put(), nullptr);if (failed(hr)){g_debug.line(l"failed to compile pixel shader!");return;}// define the vertex input layout.d3d12_input_element_desc inputelementdescs[] ={{ "position", 0, dxgi_format_r32g32b32_float, 0, 0, d3d12_input_classification_per_vertex_data, 0 },{ "color", 0, dxgi_format_r32g32b32a32_float, 0, 12, d3d12_input_classification_per_vertex_data, 0 }};// describe and create the graphics pipeline state object (pso).d3d12_graphics_pipeline_state_desc psodesc = {};psodesc.inputlayout = { inputelementdescs, _countof(inputelementdescs) };psodesc.prootsignature = _rootsignature.get();psodesc.vs = { reinterpret_cast(vertexshader->getbufferpointer()), vertexshader->getbuffersize() };psodesc.ps = { reinterpret_cast(pixelshader->getbufferpointer()), pixelshader->getbuffersize() };psodesc.rasterizerstate = cd3dx12_rasterizer_desc(d3d12_default);psodesc.blendstate = cd3dx12_blend_desc(d3d12_default);psodesc.depthstencilstate.depthenable = false;psodesc.depthstencilstate.stencilenable = false;psodesc.samplemask = uint_max;psodesc.primitivetopologytype = d3d12_primitive_topology_type_triangle;psodesc.numrendertargets = 1;psodesc.rtvformats[0] = dxgi_format_r8g8b8a8_unorm;psodesc.sampledesc.count = 1;hr = _device->creategraphicspipelinestate(&psodesc, iid_ppv_args(&_pipelinestate));if (failed(hr)){g_debug.line(l"failed to create graphics pipeline state!");return;}}void directx::_init_command_list(){hresult hr = _device->createcommandlist(0, d3d12_command_list_type_direct, _commandallocator.get(), _pipelinestate.get(), iid_ppv_args(&_commandlist));if (failed(hr)){g_debug.line(l"failed to create command list!");return;}_commandlist->close();}void directx::_init_vertex_buffer(){// define the geometry for a triangle.vertex trianglevertices[] ={{ { 0.0f, 0.25f, 0.0f }, { 1.0f, 0.0f, 0.0f, 1.0f } },{ { 0.25f, -0.25f, 0.0f }, { 0.0f, 1.0f, 0.0f, 1.0f } },{ { -0.25f, -0.25f, 0.0f }, { 0.0f, 0.0f, 1.0f, 1.0f } }};const uint vertexbuffersize = sizeof(trianglevertices);// note: using upload heaps to transfer static data like vert buffers is not // recommended. every time the gpu needs it, the upload heap will be marshalled // over. please read up on default heap usage. an upload heap is used here for // code simplicity and because there are very few verts to actually transfer.cd3dx12_heap_properties heapprops(d3d12_heap_type_upload);auto desc = cd3dx12_resource_desc::buffer(vertexbuffersize);hresult hr = _device->createcommittedresource(&heapprops,d3d12_heap_flag_none,&desc,d3d12_resource_state_generic_read,nullptr,iid_ppv_args(&_vertexbuffer));if (failed(hr)){g_debug.line(l"failed to create vertex buffer!");return;}// copy the triangle data to the vertex buffer.uint8* pvertexdatabegin;cd3dx12_range readrange(0, 0); // we do not intend to read from this resource on the cpu.hr = _vertexbuffer->map(0, &readrange, reinterpret_cast(&pvertexdatabegin));memcpy(pvertexdatabegin, trianglevertices, sizeof(trianglevertices));_vertexbuffer->unmap(0, nullptr);// initialize the vertex buffer view._vertexbufferview.bufferlocation = _vertexbuffer->getgpuvirtualaddress();_vertexbufferview.strideinbytes = sizeof(vertex);_vertexbufferview.sizeinbytes = vertexbuffersize;}void directx::_init_fence(){hresult hr = _device->createfence(0, d3d12_fence_flag_none, iid_ppv_args(&_fence));_fencevalue = 1;// create an event handle to use for frame synchronization._fenceevent = createevent(nullptr, false, false, nullptr);if (_fenceevent == nullptr){hr = hresult_from_win32(getlasterror());if (failed(hr)){g_debug.line(l"failed to create fence!");return;}}// wait for the command list to execute; we are reusing the same command // list in our main loop but for now, we just want to wait for setup to // complete before continuing.waitforpreviousframe();}void directx::waitforpreviousframe(){// waiting for the frame to complete before continuing is not best practice.// this is code implemented as such for simplicity. more advanced samples // illustrate how to use fences for efficient resource usage.// signal and increment the fence value.const uint64 fence = _fencevalue;hresult hr = _commandqueue->signal(_fence.get(), fence);if (failed(hr)){g_debug.line(l"failed to signal and increment fence!");return;}_fencevalue ;// wait until the previous frame is finished.if (_fence->getcompletedvalue() < fence){hr = _fence->seteventoncompletion(fence, _fenceevent);if (failed(hr)){g_debug.line(l"failed to set event on completion!");return;}waitforsingleobject(_fenceevent, infinite);}_frameindex = _swapchain->getcurrentbackbufferindex();}void directx::populatecommandlist(){// command list allocators can only be reset when the associated // command lists have finished execution on the gpu; apps should use // fences to determine gpu execution progress.hresult hr = _commandallocator->reset();if (failed(hr)){g_debug.line(l"failed to reset command allocator!");return;}// however, when executecommandlist() is called on a particular command // list, that command list can then be reset at any time and must be before // re-recording.hr = _commandlist->reset(_commandallocator.get(), _pipelinestate.get());if (failed(hr)){g_debug.line(l"failed to reset command list!");return;}// set necessary state._commandlist->setgraphicsrootsignature(_rootsignature.get());_commandlist->rssetviewports(1, &_viewport);_commandlist->rssetscissorrects(1, &_scissorrect);// indicate that the back buffer will be used as a render target.auto barrier = cd3dx12_resource_barrier::transition(_rendertargets[_frameindex].get(), d3d12_resource_state_present, d3d12_resource_state_render_target);_commandlist->resourcebarrier(1, &barrier);cd3dx12_cpu_descriptor_handle rtvhandle(_rtvheap->getcpudescriptorhandleforheapstart(), _frameindex, _rtvdescriptorsize);_commandlist->omsetrendertargets(1, &rtvhandle, false, nullptr);// record commands.const float clearcolor[] = { 0.0f, 0.2f, 0.4f, 1.0f };_commandlist->clearrendertargetview(rtvhandle, clearcolor, 0, nullptr);_commandlist->iasetprimitivetopology(d3d_primitive_topology_trianglelist);_commandlist->iasetvertexbuffers(0, 1, &_vertexbufferview);_commandlist->drawinstanced(3, 1, 0, 0);// indicate that the back buffer will now be used to present.barrier = cd3dx12_resource_barrier::transition(_rendertargets[_frameindex].get(), d3d12_resource_state_render_target, d3d12_resource_state_present);_commandlist->resourcebarrier(1, &barrier);hr = _commandlist->close();if (failed(hr)){g_debug.line(l"failed to close command list!");return;}}void gethardwareadapter(_idxgifactory* pfactory, _idxgiadapter** ppadapter){*ppadapter = nullptr;for (uint adapterindex = 0; ; adapterindex){_idxgiadapter* padapter = nullptr;if (dxgi_error_not_found == pfactory->enumadapterbygpupreference(adapterindex,dxgi_gpu_preference_high_performance, _uuidof(_idxgiadapter), (void**)&padapter)){// no more adapters to enumerate.break;}// check to see if the adapter supports direct3d 12, but don't create the// actual device yet.if (succeeded(d3d12createdevice(padapter, d3d_feature_level_11_0, _uuidof(id3d12device), nullptr))){*ppadapter = padapter;return;}padapter->release();}}}

 

总结

以上是尊龙游戏旗舰厅官网为你收集整理的【directx12】2.示例三角形绘制的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得尊龙游戏旗舰厅官网网站内容还不错,欢迎将尊龙游戏旗舰厅官网推荐给好友。

  • 上一篇:
  • 下一篇:
网站地图